<?php
// ----------------------------------------------------------------------
// pn-commerce Shopping Cart Solution for PostNuke
// http://pncommerce.de
// http://www.sourceforge.net/projects/pn-commerce/
//
// It is based on PostKart 0.701QA from
//                      Destin LeBlanc [ postkart@zenflesh.com ]
// ----------------------------------------------------------------------
// Source file:  $Source: /cvsroot/pn-commerce/pn-commerce/pnadminapi.php,v $
//
// Last changes from:  $Author: landseer $
//
// Revision:           $Revision: 1.184 $
//
// Date of revision    $Date: 2005/08/21 13:28:04 $
//
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------
// Purpose of this file: Displaying a simple shoppingcart on your website
//              Administrative functions
// ----------------------------------------------------------------------

require_once("modules/zCart/common.php");

/**
 * Generates a url with the given parameters using the standard
 * pnmodurl and if needed replaces the beginning with https or the sslpath
 * @param $Module string The modulename
 * @param $Section string section like admin or user
 * @param $Function string the function to call
 * @param $Args array the array of arguments for the Function
 * @return string the generated URL
 */
function pncAdminAPIModURL($Module,$Section,$Function,$Args=array())
{
    pncloadapi('user', __FILE__, __LINE__);
    return pnModAPIFunc ('pncommerce', 'user','pncModURL',
                       array(
                             'Module'=>$Module,
                             'Section'=>$Section,
                             'Function'=>$Function,
                             'Args'=>$Args));
}

/**
* returns the list of all available plugins of the given type
*
* @param type $ cm/pr
* @param allplugins $ boolean
* @return array, false on failure
*/
function pncommerce_adminapi_getAvailablePlugins($args)
{
    extract($args);
    unset($args);

    if(!pnSecAuthAction(0, 'pncommerce::', "::", ACCESS_OVERVIEW)) {
        return showerrorpage(_NOAUTH, __FILE__, __LINE__);
    }

//    $pluginstates = unserialize(pnModGetVar ('pncommerce', 'pluginstates'));
//    if (!is_array($pluginstates))$pluginstates = array();

    $allplugins = (isset($allplugins)) ? $allplugins : false;

    $plugins = array();
    $dir = opendir ("modules/pncommerce");
    while ($plugin = readdir($dir)) {
        if (ereg("pn" . $type, $plugin)) {
            $pluginname = str_replace("api.php", "", $plugin);
            $pluginname = substr($pluginname, 2, strlen($pluginname) - 2);
            if (pnSecAuthAction(0, 'pncommerce::plugin', "$type:$pluginname:", ACCESS_COMMENT)) {
                pncloadapi($pluginname, __FILE__, __LINE__);
//                if (empty($pluginstates[$pluginname]))$pluginstates[$pluginname] = _PCSS_UNINITIALIZED;
//                if (($args['onlyactive'] == false) || ($pluginstates[$pluginname] != _PCSS_UNINITIALIZED)) {
                $info = pnModAPIFunc('pncommerce', $pluginname, 'info');
                if($info<>false || $allplugins==true) {
                    $plugins[$pluginname] = array('info'  => $info,
                                                  'name' => $pluginname);
                }
            }
        }
    }
    return $plugins;
}

/**
 * Set the values for ssl access
 * @param $args['UseSSL'] bool 'on', ''
 * @param $args['SSLPath'] String optional
 * @param $args['NonSSLPath'] String optional
 */
function pncommerce_adminapi_setConfigSSL($args)
{
  if (pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN)) {
    extract($args);
    pnModSetVar('pncommerce', 'UseSSL', ($UseSSL));
    pnModSetVar('pncommerce', 'SSLPath', ($SSLPath));
    pnModSetVar('pncommerce', 'NonSSLPath', ($NonSSLPath));
  }else{
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }
}

/**
 * Gets the values for ssl access
 * @returns array
 * @return array UseSSL ('on', '') and SSLPath (string)
 */
function pncommerce_adminapi_getConfigSSL()
{
  $Result = array();
  $Result['UseSSL'] = pnModGetVar('pncommerce', 'UseSSL');
  $Result['SSLPath'] = pnModGetVar('pncommerce', 'SSLPath');
  $Result['NonSSLPath'] = pnModGetVar('pncommerce', 'NonSSLPath');
  return $Result;
}

/**
 * Set the default article values
 * @param $args['DefaultTaxExempt']  'on', ''
 * @param $args['WeightUnit']  String
 */
function pncommerce_adminapi_setConfigArticles($args)
{
  if (pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN)) {
    extract($args);
    pnModSetVar('pncommerce', 'DefaultTaxExempt', ($DefaultTaxExempt));
    pnModSetVar('pncommerce', 'WeightUnit', ($WeightUnit));
  }else{
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }
}

/**
 * Gets the default article values
 * @returns array
 * @return array DefaultTaxExempt 'on', ''
 * @return array WeightUnit String
 */
function pncommerce_adminapi_getConfigArticles()
{
  $Result = Array();
  $Result['DefaultTaxExempt'] =
    pnModGetVar('pncommerce', 'DefaultTaxExempt');
  $Result['WeightUnit'] =
    pnModGetVar('pncommerce', 'WeightUnit');
  return $Result;
}

/**
 * Set the general default values
 * @param $args['DisableIntl']  ('on', '')
 */
function pncommerce_adminapi_setConfigGeneral($args)
{
    if (pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN)) {
        extract($args);
        pnModSetVar('pncommerce', 'DisableIntl', ($DisableIntl));
    }else{
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
}

/**
 * Gets the general default values
 * @returns array
 * @return array DisableIntl ('on', '')
 */
function pncommerce_adminapi_getConfigGeneral()
{
    return array( 'DisableIntl' => pnModGetVar('pncommerce', 'DisableIntl'));
}

/**
 * Set the catalog values
 * @param $args['ShowItems']  integer
 */
function pncommerce_adminapi_setConfigCatalog($args)
{
    if (pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN)) {
        extract($args);
        pnModSetVar('pncommerce', 'ShowItems', $ShowItems );
    }else{
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
}

/**
 * Gets the catalog values
 * @returns array
 * @return array ShowItems (integer) )
 */
function pncommerce_adminapi_getConfigCatalog()
{
    return array( 'ShowItems' => pnModGetVar('pncommerce', 'ShowItems'));

}

/**
 * Set the locale settings
 * @param $args['Locale'] String optional
 * @param $args['DecimalDelimiter'] String optional
 * @param $args['ThousandsSeparator'] String optional
 * @param $args['CurrencySymbol'] String optional
 * @param $args['IntlCurrencySymbol'] String optional
 * @param $args['DefaultCurrencySymbol'] String optional
 * @param $args['DateFormat'] String optional
 * @param $args['TimeFormat'] String optional
 */
function pncommerce_adminapi_setConfigLocale($args)
{
    if (pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        extract($args);
        pnModSetVar('pncommerce', 'Locale', $Locale);
        pnModSetVar('pncommerce', 'DateFormat', $DateFormat);
        pnModSetVar('pncommerce', 'TimeFormat', $TimeFormat);
        pnModSetVar('pncommerce', 'DecimalDelimiter', $DecimalDelimiter);
        pnModSetVar('pncommerce', 'ThousandsSeparator', $ThousandsSeparator );
        pnModSetVar('pncommerce', 'CurrencySymbol', $CurrencySymbol );
        pnModSetVar('pncommerce', 'IntlCurrencySymbol', $IntlCurrencySymbol );
        pnModSetVar('pncommerce', 'DefaultCurrencySymbol', $DefaultCurrencySymbol );
        return true;
    }
    else
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
}

/**
 * Gets the locale settings
 * @returns array
 * @return array Locale(string),
 *               DecimalDelimiter(string),
 *               ThousandsSeparator(string),
 *               CurrencySymbol(string),
 *               IntlCurrencySymbol(string),
 *               DefaultCurrencySymbol(int)
 *               DateFormat(string)
 *               TimeFormat(string)
 */
function pncommerce_adminapi_getConfigLocale()
{
    return array( 'Locale'             => pnModGetVar('pncommerce', 'Locale'),
                  'DateFormat'         => pnModGetVar('pncommerce', 'DateFormat'),
                  'TimeFormat'         => pnModGetVar('pncommerce', 'TimeFormat'),
                  'DecimalDelimiter'   => pnModGetVar('pncommerce', 'DecimalDelimiter'),
                  'ThousandsSeparator' => pnModGetVar('pncommerce', 'ThousandsSeparator'),
                  'CurrencySymbol'     => pnModGetVar('pncommerce', 'CurrencySymbol'),
                  'IntlCurrencySymbol' => pnModGetVar('pncommerce', 'IntlCurrencySymbol'),
                  'DefaultCurrencySymbol' => pnModGetVar('pncommerce', 'DefaultCurrencySymbol'));
}

/**
 * Converts a country specific formatted number within a string into
 * a double or int value, returns (int)0 when the string contains no numeric
 * value.
 * @param $args['value'] String
 * @returns double or int
 * @return double if decimal delimiter was found
 * @return int if no decimal delimiter was found
 */
function pncommerce_adminapi_convertToNumber($args)
{
    extract($args);

    $decimalDelimiter = pnModGetVar('pncommerce', 'DecimalDelimiter');
    $thousandsSeparator = pnModGetVar('pncommerce', 'ThousandsSeparator');

    // Extract the numeric part with a regular expression:
    // Divide the string into four parts:
    // 1. everything non numeric
    // 2. at least one digit and all following digits and thousands
    //    separators (can be empty for values like "$ .12"
    // 3. the fractional part: decimal delimiter and following digits and
    //    thousands separators (can be empty for values like "$ 42")
    // 4. all the rest
    // At the end we use the second and third part.
    // All separators and delimiters have to be in character classes because
    // because in regular expressions they can become wildcards
    $value = ereg_replace('([^0-9' . $decimalDelimiter . ']*)' . // non numeric
                          '([0-9]+[0-9' . $thousandsSeparator . ']*)*' . // integer
                          '([' . $decimalDelimiter . '][0-9]+[0-9' . $thousandsSeparator . ']*)*' . // fractional
                          '(.*)',   // the rest
                          '\\2\\3', // replace with second and third part
                          $value);
    // remove thousands separators
    if ($thousandsSeparator != $decimalDelimiter)
    {
        $value = str_replace($thousandsSeparator, "", $value);
    }
    // now replace country specific decimal delimiter with decimal point
    $value = str_replace($decimalDelimiter, ".", $value);
    if (strlen($value) == 0)
    {
        $result = (int)0;
    }
    if (strpos($value, '.') === false)
    {
        $result = (int)$value;
    }
    else
    {
        $result = (double)$value;
    }
    return $result;
}

/**
 * Set the values for StorePolicies
 * @param $args['StorePolicies'] String
 * @param $args['EnablePolicies'] 'on', ''
 * @param $args['AgreeToPolicies'] 'on', ''
 * @param $args['AcknowledgeLaw'] 'on', ''
 */
function pncommerce_adminapi_setConfigStorePolicies($args)
{
  if (pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN)) {
    extract($args);
    pnModSetVar('pncommerce', 'StorePolicies', $StorePolicies);
    pnModSetVar('pncommerce', 'EnablePolicies', $EnablePolicies);
    pnModSetVar('pncommerce', 'AgreeToPolicies', $AgreeToPolicies);
    pnModSetVar('pncommerce', 'AcknowledgeLaw', $AcknowledgeLaw);
  }else{
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }
}

/**
 * Gets the values for ssl access
 * @returns array
 * @return array 'StorePolicies' (string), 'EnablePolicies' ('on', ''), 'AgreeToPolicies' ('on', ''), 'AcknowledgeLaw' ('on', '')
 */
function pncommerce_adminapi_getConfigStorePolicies()
{
  $Result = Array();
  $Result['StorePolicies'] = pnModGetVar('pncommerce', 'StorePolicies');
  $Result['EnablePolicies'] = pnModGetVar('pncommerce', 'EnablePolicies');
  $Result['AgreeToPolicies'] = pnModGetVar('pncommerce', 'AgreeToPolicies');
  $Result['AcknowledgeLaw'] = pnModGetVar('pncommerce', 'AcknowledgeLaw');
  return $Result;
}

/**
 * Set a template
 * @param $args['IndexTemplate'] String
 */
function pncommerce_adminapi_setConfigTemplate($args)
{
  if (pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN)) {
    extract($args);
    pnModSetVar('pncommerce', 'IndexTemplate', $IndexTemplate);
  }else{
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }
}

/**
 * Gets the values for ssl access
 * @returns array
 * @return array 'IndexTemplate' (string)
 */
function pncommerce_adminapi_getConfigTemplate()
{
  $Result = Array();
  $Result['IndexTemplate'] = pnModGetVar('pncommerce', 'IndexTemplate');
  return $Result;
}

/**
 * Set the values for supplier data
 * @param $args['Company'] String optional
 * @param $args['Address1'] String optional
 * @param $args['Address2'] String optional
 * @param $args['City'] String optional
 * @param $args['State'] String optional
 * @param $args['Zip'] String optional
 * @param $args['Country'] String optional
 * @param $args['Phone'] String optional
 * @param $args['Web'] String optional
 * @param $args['Email'] String optional
 * @param $args['Bank'] String optional
 * @param $args['Bankcode'] String optional
 * @param $args['Account'] String optional
 * @param $args['Fax'] String optional
 * @param $args['AddressFormat'] String optional
 * @param $args['ShopIntroTemplateID'] int optional
 * @param $args['DefaultCategoryViewTemplateID'] int optional
 * @param $args['DefaultItemViewTemplateID'] int optional
 * @param $args['MailTemplateID'] int optional
 * @param $args['InternalMailTemplateID'] int optional
 * @param $args['InvoiceTemplateID'] int optional
 * @param $args['PrintInvoiceTemplateID'] int optional
 * @param $args['MaximumCartLifetime'] int optional
 * @param $args['MaxItemsToRemember'] int optional
 * @param $args['MaximumLogLevel'] int optional
 * @param $args['MinimumOrderValue'] String optional
 * @param $args['JumpToCartviewAfterAdd'] String optional
 * @param $args['VatIncluded'] String optional
 * @param $args['UseAuthKeys'] String optional
 */
function pncommerce_adminapi_setConfigSupplier($args)
{
  if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }
  extract($args);
  if (isset($Company)) {
    pnModSetVar('pncommerce', 'Company', $Company);
  }
  if (isset($Address1)) {
    pnModSetVar('pncommerce', 'Address1', $Address1);
  }
  if (isset($Address2)) {
    pnModSetVar('pncommerce', 'Address2', $Address2);
  }
  if (isset($City)) {
    pnModSetVar('pncommerce', 'City', $City);
  }
  if (isset($State)) {
    pnModSetVar('pncommerce', 'State', $State);
  }
  if (isset($Zip)) {
    pnModSetVar('pncommerce', 'Zip', $Zip);
  }
  if (isset($Phone)) {
    pnModSetVar('pncommerce', 'Phone', $Phone);
  }
  if (isset($Web)) {
    pnModSetVar('pncommerce', 'Web', $Web);
  }
  if (isset($Country)) {
    pnModSetVar('pncommerce', 'Country', $Country);
  }
  if (isset($Email)) {
    pnModSetVar('pncommerce', 'Email', $Email);
  }
  if (isset($Bank)) {
    pnModSetVar('pncommerce', 'Bank', $Bank);
  }
  if (isset($Bankcode)) {
    pnModSetVar('pncommerce', 'Bankcode', $Bankcode);
  }
  if (isset($Account)) {
    pnModSetVar('pncommerce', 'Account', $Account);
  }
  if (isset($Fax)) {
    pnModSetVar('pncommerce', 'Fax', $Fax);
  }
  if (isset($AddressFormat)) {
    pnModSetVar('pncommerce', 'AddressFormat', $AddressFormat);
  }
  if (isset($ShopIntroTemplateID)) {
    pnModSetVar('pncommerce', 'ShopIntroTemplateID', $ShopIntroTemplateID);
  }
  if (isset($DefaultCategoryViewTemplateID)) {
    pnModSetVar('pncommerce', 'DefaultCategoryViewTemplateID', $DefaultCategoryViewTemplateID);
  }
  if (isset($DefaultItemViewTemplateID)) {
    pnModSetVar('pncommerce', 'DefaultItemViewTemplateID', $DefaultItemViewTemplateID);
  }
  if (isset($MailTemplateID)) {
    pnModSetVar('pncommerce', 'MailTemplateID', $MailTemplateID);
  }
  if (isset($InternalMailTemplateID)) {
    pnModSetVar('pncommerce', 'InternalMailTemplateID', $InternalMailTemplateID);
  }
  if (isset($InvoiceTemplateID)) {
    pnModSetVar('pncommerce', 'InvoiceTemplateID', $InvoiceTemplateID);
  }
  if (isset($PrintInvoiceTemplateID)) {
    pnModSetVar('pncommerce', 'PrintInvoiceTemplateID', $PrintInvoiceTemplateID);
  }
  if (isset($MaximumCartLifetime)) {
    pnModSetVar('pncommerce', 'MaximumCartLifetime', $MaximumCartLifetime);
  }
  if (isset($MaxItemsToRemember)) {
    pnModSetVar('pncommerce', 'MaxItemsToRemember', $MaxItemsToRemember);
  }
  if (isset($MaximumLogLevel)) {
    pnModSetVar('pncommerce', 'MaximumLogLevel', $MaximumLogLevel);
  }
  if (isset($MinimumOrderValue)) {
    pnModSetVar('pncommerce', 'MinimumOrderValue', $MinimumOrderValue);
  }
  if (isset($TaxNumber)) {
    pnModSetVar('pncommerce', 'TaxNumber', $TaxNumber);
  }
  pnModSetVar('pncommerce', 'JumpToCartviewAfterAdd', $JumpToCartviewAfterAdd);
  pnModSetVar('pncommerce', 'VatIncluded', $VatIncluded);
  pnModSetVar('pncommerce', 'UseAuthKeys', $UseAuthKeys);

}

/**
 * Gets the values for supplier data
 * just set the keys and the Resultset will have the proper values in it, if available
 * If you don't bypass any parameter, all values will be made available
 * @param $args['Company'] String optional
 * @param $args['Address1'] String optional
 * @param $args['Address2'] String optional
 * @param $args['City'] String optional
 * @param $args['State'] String optional
 * @param $args['Zip'] String optional
 * @param $args['Country'] String optional
 * @param $args['Phone'] String optional
 * @param $args['Web'] String optional
 * @param $args['Email'] String optional
 * @param $args['Bank'] String optional
 * @param $args['Bankcode'] String optional
 * @param $args['Account'] String optional
 * @param $args['Fax'] String otional
 * @param $args['AddressFormat'] String optional
 * @param $args['ShopIntroTemplateID'] String optional
 * @param $args['DefaultCategoryViewTemplateID'] String optional
 * @param $args['DefaultItemViewTemplateID'] String optional
 * @param $args['MailTemplateID'] String optional
 * @param $args['InternalMailTemplateID'] String optional
 * @param $args['InvoiceTemplateID'] String optional
 * @param $args['PrintInvoiceTemplateID'] String optional
 * @param $args['MaximumCartLifetime'] String optional
 * @param $args['MaxItemsToRemember'] String optional
 * @param $args['MaximumLogLevel'] String optional
 * @param $args['MinimumOrderValue'] String optional
 * @param $args['JumpToCartviewAfterAdd'] String optional
 * @param $args['VatIncluded'] String optional
 * @param $args['UseAuthKeys'] String optional
 * @param $args['TaxNumber'] String optional
 * @returns array
 * @return array all as param provided fields
 * @return  it is empty if the field doesn't exist
 */
function pncommerce_adminapi_getConfigSupplier($args)
{
    if (!$args )
    {
        $args = Array();
        $args['Company'] = ' ';
        $args['Address1'] = ' ';
        $args['Address2'] = ' ';
        $args['City'] = ' ';
        $args['State'] = ' ';
        $args['Zip'] = ' ';
        $args['Country'] = ' ';
        $args['Phone'] = ' ';
        $args['Web'] = ' ';
        $args['Email'] = ' ';
        $args['Bank'] = ' ';
        $args['Bankcode'] = ' ';
        $args['Account'] = ' ';
        $args['Fax'] = ' ';
        $args['AddressFormat'] = ' ';
        $args['ShopIntroTemplateID'] = ' ';
        $args['DefaultCategoryViewTemplateID'] = ' ';
        $args['DefaultItemViewTemplateID'] = ' ';
        $args['MailTemplateID'] = ' ';
        $args['InternalMailTemplateID'] = ' ';
        $args['InvoiceTemplateID'] = ' ';
        $args['PrintInvoiceTemplateID'] = ' ';
        $args['MaximumCartLifetime'] = ' ';
        $args['MaxItemsToRemember'] = ' ';
        $args['MaximumLogLevel'] = ' ';
        $args['MinimumOrderValue'] = ' ';
        $args['JumpToCartviewAfterAdd'] = ' ';
        $args['VatIncluded'] = ' ';
        $args['UseAuthKeys'] = ' ';
        $args['TaxNumber'] = ' ';
    }
    //Maybe we should check if the key is one of the master data fields... Comments?
    $Result = array();
    $keys = array_keys($args);
    foreach($keys as $key)
    {
        $Result[$key] = pnModGetVar('pncommerce', $key);
    }
    return $Result;
}

/**
 * Set the values for Thumbnail creation
 * @param $args['TNUploadDisable'] 'on', ''
 * @param $args['TNIgnoreDisable'] 'on', ''
 * @param $args['TNCreateDisable'] 'on', ''
 * @param $args['TNCreateMethod'] string : gd or im
 * @param $args['TNIMPath'] string optional
 * @param $args['TNWidth'] string optional
 * @param $args['TNHeight'] string optional
 * @param $args['UseImageReplacement'] string optional
 * @param $args['ItemImageReplacement'] string optional
 * @param $args['ItemImageTNReplacement'] string optional
 * @param $args['CategoryImageReplacement'] string optional
 * @param $args['CategoryImageTNReplacement'] string optional
 */
function pncommerce_adminapi_setConfigThumbnail($args)
{
  if (pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN)) {
    extract($args);
    pnModSetVar('pncommerce', 'TNUploadDisable', $TNUploadDisable);
    pnModSetVar('pncommerce', 'TNIgnoreDisable', $TNIgnoreDisable);
    pnModSetVar('pncommerce', 'TNCreateDisable', $TNCreateDisable);
    pnModSetVar('pncommerce', 'TNCreateMethod', $TNCreateMethod);
    pnModSetVar('pncommerce', 'TNWidth', $TNWidth);
    pnModSetVar('pncommerce', 'TNHeight', $TNHeight);
    pnModSetVar('pncommerce', 'UseImageReplacements', $UseImageReplacements );
    pnModSetVar('pncommerce', 'ItemImageReplacement', $ItemImageReplacement);
    pnModSetVar('pncommerce', 'ItemImageTNReplacement', $ItemImageTNReplacement);
    pnModSetVar('pncommerce', 'CategoryImageReplacement', $CategoryImageReplacement);
    pnModSetVar('pncommerce', 'CategoryImageTNReplacement', $CategoryImageTNReplacement);
    if (isset($TNIMPath)) {
      pnModSetVar('pncommerce', 'TNIMPath', $TNIMPath);
    }
  }else{
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }
}

/**
 * Gets the values for Thumbnail creation
 * @returns array
 * @return array TNUploadDisable('on', ''), TNIgnoreDisable('on', ''), TNCreateDisable('on', ''), TNCreateMethod('on', ''), TNIMPath, TNWidth, TNHeight
 */
function pncommerce_adminapi_getConfigThumbnail()
{
  $Result = Array();
  $Result['TNUploadDisable'] = pnModGetVar('pncommerce', 'TNUploadDisable');
  $Result['TNIgnoreDisable'] = pnModGetVar('pncommerce', 'TNIgnoreDisable');
  $Result['TNCreateDisable'] = pnModGetVar('pncommerce', 'TNCreateDisable');
  $Result['TNCreateMethod'] = pnModGetVar('pncommerce', 'TNCreateMethod');
  $Result['TNIMPath'] = pnModGetVar('pncommerce', 'TNIMPath');
  $Result['TNWidth'] = pnModGetVar('pncommerce', 'TNWidth');
  $Result['TNHeight'] = pnModGetVar('pncommerce', 'TNHeight');
  $Result['UseImageReplacements'] = pnModGetVar('pncommerce', 'UseImageReplacements');
  $Result['ItemImageReplacement'] = pnModGetVar('pncommerce', 'ItemImageReplacement' );
  $Result['ItemImageTNReplacement'] =  pnModGetVar('pncommerce', 'ItemImageTNReplacement' );
  $Result['CategoryImageReplacement'] = pnModGetVar('pncommerce', 'CategoryImageReplacement');
  $Result['CategoryImageTNReplacement'] = pnModGetVar('pncommerce', 'CategoryImageTNReplacement');
  return $Result;
}

/**
 * Store an article in the database
 * The Article must exist!
 * (Otherwise use add!)
 * @param $args['ItemID'] string
 * @param $args['Scheme_ID'] int
 * @param $args['ItemSKU'] string
 * @param $args['ItemName'] string
 * @param $args['ItemCost'] double
 * @param $args['Weight'] int(8)
 * @param $args['VATID'] [1..9]
 * @param $args['TaxExempt'] 'on', ''
 * @param $args['Category'] string
 * @param $args['CategoryID'] int
 * @param $args['ItemDescription'] string
 * @param $args['image'] string (Filename to upload)
 * @param $args['tngen'] string (upload, create, ignore)
 * @param $args['file'] string optional (filename of the prepared, needed if tngen=upload)
 * @param $args['tnwidth'] string optional (Width for the generated thumbnail, needed if tngen=create)
 * @param $args['tnheight'] string optional (Height for the generated thumbnail, needed if tngen=create)
 * @param $args['QuantityOnHand'] number
 * @param $args['IgnoreQuantity'] 'on', ''
 */
function pncommerce_adminapi_ArticleStore($args)
{
    extract($args);

    $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$CategoryID));
    if (!pnSecAuthAction(0,
                       'pncommerce::category',
                       $CName.'::'.$CategoryID,
                       ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
//    setlocale(LC_ALL, pnModGetVar( '/PNConfig', 'locale' ) );

    list($dbconn) = pnDBGetConn();
    $itemsTable = pnConfigGetVar('prefix').'_pncommerce_items';
  //              $itemsTable = $pntable[pncommerce_items];

    pncloadapi('user', __FILE__, __LINE__);

    $ItemCost = number_format($ItemCost, 3, '.', '');//ereg_replace( ",", ".", $ItemCost );
    $Weight = number_format($Weight, 4, '.', '');//ereg_replace( ",", ".", $Weight );

    $sql = "UPDATE $itemsTable SET
                        scheme_id='".pnVarPrepForStore($Scheme_ID)."',
                        ItemSKU='".pnVarPrepForStore($ItemSKU)."',
                        ItemName='".pnVarPrepForStore($ItemName)."',
                        ItemDescription='".pnVarPrepForStore($ItemDescription)."',
                        ItemCost='".pnVarPrepForStore($ItemCost)."',
                        Weight='".pnVarPrepForStore($Weight)."',
                        Category='".pnVarPrepForStore($CategoryID)."',
                        ItemQuantity='".pnVarPrepForStore($QuantityOnHand)."',VATID='".pnVarPrepForStore($VATID)."',
                        IgnoreQuantity='".pnVarPrepForStore($IgnoreQuantity)."',
                        TaxExempt='".pnVarPrepForStore($TaxExempt)."'
                        WHERE ItemID='".pnVarPrepForStore($ItemID)."'";
    if($Scheme_ID!=$oldScheme_ID){
        pnModAPIFunc( 'pncommerce', 'admin','stripProperties',array('object_id'=>$ItemID,'oldscheme_id'=>$oldScheme_ID,'scheme_id'=>$Scheme_ID));
        pnModAPIFunc( 'pncommerce', 'admin','refreshProperties',array('object_id'=>$ItemID,'scheme_id'=>$Scheme_ID));
    }
    else foreach($PropertiesData as $prop)
    {
        pnModAPIFunc( 'pncommerce', 'admin','propertydataStore',$prop);
    }

    $dbconn->Execute($sql);
    // Check for an error with the database code, and if so set an appropriate
    // error message and return
    if ($dbconn->ErrorNo() != 0)
    {
        pnSessionSetVar('errormsg', "error:".$dbconn->ErrorMsg() );
        return false;
    }
    return true;
}

/**
 * add property in the database
 * @param $args['scheme_id'] int
 * @param $args['type'] string
 * @param $args['name'] string
 * @param $args['config'] mixed
 * @param $args['sortorder'] int
 * @return boolean true on success
 */

function pncommerce_adminapi_propertyAdd($args)
{
    if (!pnSecAuthAction(0,
                       'pncommerce::property',
                       '::', ACCESS_ADD))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
    if(is_array($args['config'])){
      $args['config']=serialize($args['config']);
    }
    if(strlen($args['config'])>250){
      return showerrorpage(_PNC_PROPERTYCONFIGTOOLONG, __FILE__, __LINE__);
    }
    list($dbconn, $pntable) = pncOpenDB();
    $propertiestable = $pntable['pncommerce_properties'];
    $propertiescolumn = &$pntable['pncommerce_properties_column'];
    $sql = "INSERT INTO $propertiestable
                ($propertiescolumn[scheme_id],
                $propertiescolumn[name],
                $propertiescolumn[type] ,
                $propertiescolumn[config],
                $propertiescolumn[hidden],
                $propertiescolumn[sortorder])
                VALUES
                ('".pnVarPrepForStore((int)$args['scheme_id'])."',
                 '".pnVarPrepForStore($args['name'])."',
                 '".pnVarPrepForStore($args['type'])."',
                 '".pnVarPrepForStore($args['config'])."',
                 '".pnVarPrepForStore((int)$args['hidden'])."',
                 '".pnVarPrepForStore((int)$args['sortorder'])."')";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
    $property_id = $dbconn->PO_Insert_ID($pntable['pncommerce_properties'], 'property_id');
    pncCloseDB($result);

    // after adding a new property we have to add propertydata sets for each
    // object using this scheme
    // the schemes type is submitted in scheme_type and so we can read
    // all objects using this scheme from the correct table
    switch($args['scheme_type']) {
        case PNC_ITEMSCHEME:
            $object_type = PNC_ITEMPROP;
            $itemstable = $pntable['pncommerce_items'];
            $itemscolumn = &$pntable['pncommerce_items_column'];
            $sql = "SELECT " . $itemscolumn['ItemID'] . " AS object_id FROM $itemstable WHERE " . $itemscolumn['scheme_id'] . "='" . (int)pnVarPrepForStore($args['scheme_id']) . "'";
            break;
        case PNC_CATEGORYSCHEME:
            break;
        case PNC_CONFIGSCHEME:
            break;
        case PNC_USERSCHEME:
            break;
        default:
            return showerrorpage(_MODARGSERROR, __FILE__, __LINE__);

    }
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
    while (!$result->EOF) {
        $row = $result->GetRowAssoc(false);
        pnModAPIFunc('pncommerce', 'admin', 'propertydataAdd',
                      array('property_id'   => $property_id,
                            'object_id'     => $row['object_id'],
                            'object_type'   => $object_type));
        $result->MoveNext();
    }
    pncCloseDB($result);

    return true;
}

/**
 * deletes a property in the database
 * @param $args['property_id'] int
 * @return boolean true on success
 */

function pncommerce_adminapi_propertyDelete($args)
{
    if (!pnSecAuthAction(0,
                       'pncommerce::property',
                       '::', ACCESS_DELETE))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
    list($dbconn, $pntable) = pncOpenDB();
    $propertiestable = $pntable['pncommerce_properties'];
    $propertiescolumn = &$pntable['pncommerce_properties_column'];
    $sql = "DELETE FROM $propertiestable WHERE $propertiescolumn[property_id]='".pnVarPrepForStore((int)$args['property_id'])."'";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
    pncCloseDB();

    $propertiesdatatable = $pntable['pncommerce_propertiesdata'];
    $propertiesdatacolumn = &$pntable['pncommerce_propertiesdata_column'];
    $sql = "DELETE FROM $propertiesdatatable WHERE $propertiesdatacolumn[property_id]='".pnVarPrepForStore((int)$args['property_id'])."'";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
    pncCloseDB();
    return true;
}

/**
 * deletes the property data of one object that belong to the given scheme
 * @param $args['scheme_id'] int
 * @param $args['object_id'] int
 * @param $args['oldscheme_id'] int
 * @return boolean true on success
 */
function pncommerce_adminapi_stripProperties($args)
{
    if (!pnSecAuthAction(0,
                       'pncommerce::property',
                       '::', ACCESS_DELETE))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
//$args['scheme_id']  is necessary to remove only fields that are on the old scheme
//but not in the new one. Fir simplicity we remove all atm and refresh them afterwards
    list($dbconn, $pntable) = pncOpenDB();
    $propertiestable = $pntable['pncommerce_properties'];
    $propertiescolumn = &$pntable['pncommerce_properties_column'];
    $sql = "SELECT $propertiescolumn[property_id] FROM $propertiestable WHERE $propertiescolumn[scheme_id]='".pnVarPrepForStore((int)$args['oldscheme_id'])."'";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
    $rem_propids=array();
    for (;$result->EOF == false;$result->MoveNext()) {
        list($id)=$result->fields;
        $rem_propids[] = $id;
    }
    pncCloseDB($result);

    if(!empty($rem_propids))
    {
        $propertiesdatatable = $pntable['pncommerce_propertiesdata'];
        $propertiesdatacolumn = &$pntable['pncommerce_propertiesdata_column'];
        $first=true;
        $sql = "DELETE FROM $propertiesdatatable
                    WHERE $propertiesdatacolumn[object_id]='".pnVarPrepForStore((int)$args['object_id'])."'
                    AND (";
        foreach($rem_propids as $id)
        {
            if(!$first)
            {
               $sql.=" OR ";
            } else $first=false;
            $sql.=" $propertiesdatacolumn[property_id]='".pnVarPrepForStore((int)$id)."'";
        }
        $sql.=")";
        $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
        pncCloseDB($result);
    }
    return true;
}

/**
 * Store an property in the database
 * The property must exist!
 * (Otherwise use add!)
 * @param $args['property_id'] int
 * @param $args['scheme_id'] int
 * @param $args['type'] string
 * @param $args['name'] string
 * @param $args['config'] string
 * @param $args['sortorder'] int
 * @return boolean true on success
 */
function pncommerce_adminapi_propertyStore($args)
{
    if (!pnSecAuthAction(0,
                       'pncommerce::property',
                       '::', ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
    if(is_array($args['config'])){
      $args['config']=serialize($args['config']);
    }
    if(strlen($args['config'])>250){
      return showerrorpage(_PNC_PROPERTYCONFIGTOOLONG, __FILE__, __LINE__);
    }
    list($dbconn, $pntable) = pncOpenDB();
    $propertiestable = $pntable['pncommerce_properties'];
    $propertiescolumn = &$pntable['pncommerce_properties_column'];
    $sql = "UPDATE $propertiestable SET
                $propertiescolumn[scheme_id] = '".pnVarPrepForStore((int)$args['scheme_id'])."',
                $propertiescolumn[name] = '".pnVarPrepForStore($args['name'])."',
                $propertiescolumn[type] = '".pnVarPrepForStore($args['type'])."',
                $propertiescolumn[config] = '".pnVarPrepForStore($args['config'])."',
                $propertiescolumn[hidden] = '".(int)pnVarPrepForStore($args['hidden'])."'
        WHERE $propertiescolumn[property_id] = '".pnVarPrepForStore((int)$args['property_id'])."'";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);

    pncCloseDB($result);
    return true;
}

/**
 * Store an propertydata in the database
 * The propertydata must exist!
 * (Otherwise use add!)
 * @param $args['propertydata_id'] int
 * @param $args['property_id'] int
 * @param $args['object_id'] int
 * @param $args['object_type'] int
 * @param $args['integerfield'] int
 * @param $args['stringfield'] string
 * @param $args['longtextfield'] longtext
 * @return boolean true on success
 */
function pncommerce_adminapi_propertydataStore($args)
{
    if (!pnSecAuthAction(0,
                       'pncommerce::item',
                       '::', ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
    list($dbconn, $pntable) = pncOpenDB();
    $propertiesdatatable = $pntable['pncommerce_propertiesdata'];
    $propertiesdatacolumn = &$pntable['pncommerce_propertiesdata_column'];
    $sql = "UPDATE $propertiesdatatable SET
                $propertiesdatacolumn[propertydata_id] = '".pnVarPrepForStore((int)$args['propertydata_id'])."',
                $propertiesdatacolumn[property_id] = '".pnVarPrepForStore((int)$args['property_id'])."',
                $propertiesdatacolumn[object_id] = '".pnVarPrepForStore((int)$args['object_id'])."',
                $propertiesdatacolumn[object_type] = '".pnVarPrepForStore((int)$args['object_type'])."',
                $propertiesdatacolumn[integerfield] = '".pnVarPrepForStore((int)$args['integerfield'])."',
                $propertiesdatacolumn[stringfield] = '".pnVarPrepForStore($args['stringfield'])."',
                $propertiesdatacolumn[longtextfield] = '".pnVarPrepForStore($args['longtextfield'])."'
        WHERE $propertiesdatacolumn[propertydata_id] = '".pnVarPrepForStore($args['propertydata_id'])."'";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
    pncCloseDB($result);
    return true;
}

/**
 * Add an propertydata to the database
 * @param $args['property_id'] int
 * @param $args['object_id'] int
 * @param $args['object_type'] int
 * @param $args['integerfield'] int
 * @param $args['stringfield'] string
 * @param $args['longtextfield'] longtext
 * @return boolean true on success
 */
function pncommerce_adminapi_propertydataAdd($args)
{
    if (!pnSecAuthAction(0,
                       'pncommerce::item',
                       '::', ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
    list($dbconn, $pntable) = pncOpenDB();
    $propertiesdatatable = $pntable['pncommerce_propertiesdata'];
    $propertiesdatacolumn = &$pntable['pncommerce_propertiesdata_column'];
    $sql = "INSERT INTO $propertiesdatatable
                ($propertiesdatacolumn[property_id],
                $propertiesdatacolumn[object_id],
                 $propertiesdatacolumn[object_type],
                $propertiesdatacolumn[integerfield],
                $propertiesdatacolumn[stringfield],
                $propertiesdatacolumn[longtextfield])
                VALUES
                ('".(int)pnVarPrepForStore($args['property_id'])."',
                 '".(int)pnVarPrepForStore($args['object_id'])."',
                '".(int)pnVarPrepForStore($args['object_type'])."',
                 '".(int)pnVarPrepForStore($args['integerfield'])."',
                 '".pnVarPrepForStore($args['stringfield'])."',
                 '".pnVarPrepForStore($args['longtextfield'])."')";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
    pncCloseDB($result);
    return true;
}

/**
 * Add an article to the database
 * @param $args['ItemSKU'] string Must be unique
 * @param $args['ItemName'] string
 * @param $args['ItemCost'] double
 * @param $args['Scheme_ID'] int
 * @param $args['Weight'] int(8)
 * @param $args['TaxExempt'] 'on', ''
 * @param $args['CategoryID'] string
 * @param $args['VATID'] [1..9]
 * @param $args['ItemDescription'] string
 * @param $args['image'] string (Filename to upload)
 * @param $args['tngen'] string (upload, create, ignore)
 * @param $args['file'] string optional (filename of the prepared, needed if tngen=upload)
 * @param $args['tnwidth'] string optional (Width for the generated thumbnail, needed if tngen=create)
 * @param $args['tnheight'] string optional (Height for the generated thumbnail, needed if tngen=create)
 * @param $args['QuantityOnHand'] number
 * @param $args['IgnoreQuantity'] 'on', ''
 * @return ItemID integer
 */
function pncommerce_adminapi_ArticleAdd($args)
{
    extract($args);
    $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$args['CategoryID']));
    if (!pnSecAuthAction(0, 'pncommerce::category', $CName.'::'.$args['CategoryID'], ACCESS_ADD)) {
     return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    list($dbconn) = pnDBGetConn();
    $itemsTable = pnConfigGetVar('prefix').'_pncommerce_items';

    $sql = "INSERT INTO $itemsTable (ItemSKU) VALUES ('".pnVarPrepForStore($ItemSKU)."')";
    $dbconn->Execute($sql);
    // Check for an error with the database code, and if so set an appropriate
    // error message and return
    if ($dbconn->ErrorNo() != 0) {
        pnSessionSetVar('errormsg', _PNC_GETFAILED);
        return false;
    }
    //Now we fetch the ID to store all of the data
    //No error checking needed, because the prior action was a success
    $args['ItemID'] = $dbconn->PO_Insert_ID($itemsTable, 'ItemID');
    //Why the effort?
    //So we have to maintain only one function for new fields
    pncommerce_adminapi_ArticleStore($args);
    return $args;
}



/**
 * Deletes an article in the database and the coresponding thumbnails and product images
 * @param $args['ItemID'] string
 */
function pncommerce_adminapi_ArticleDelete($args)
{
    pncloadapi('user', __FILE__, __LINE__);

    extract($args);
    list($catID)=pnModAPIFunc('pncommerce','user','readfromdb', array('table' => 'items', 'fields' => array('category'), 'required' => array('itemid', $ItemID)) );
    $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$catID));
    if (!pnSecAuthAction(0, 'pncommerce::category', $CName.'::'.$catID, ACCESS_DELETE)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    list($dbconn) = pnDBGetConn();
    $itemsTable = pnConfigGetVar('prefix').'_pncommerce_items';
    $sql = "DELETE FROM $itemsTable WHERE ItemID='".pnVarPrepForStore($ItemID)."'";
    $dbconn->Execute($sql);
    // Check for an error with the database code, and if so set an appropriate
    // error message and return
    if ($dbconn->ErrorNo() != 0) {
        pnSessionSetVar('errormsg', _PNC_GETFAILED);
        return false;
    }

    $delargs['itemID']=$ItemID;
    $delargs['delimage']='true';
    $delargs['delimagetn']='true';
    pncommerce_adminapi_ArticleImagesRemove($delargs);
    return true;
}

/**
 * tests if the SKU is valid. (not taken by another item,...)
 * @param $args['ItemID'] string
 * @param $args['ItemSKU'] string
 * @return bool true if ItemSKU is valid
 */
function pncommerce_adminapi_ArticleSKUValid($args)
{
    extract($args);
    list($dbconn) = pnDBGetConn();
    $itemsTable = pnConfigGetVar('prefix').'_pncommerce_items';
    $sql =
      "SELECT ItemID,ItemSKU FROM $itemsTable WHERE ItemSKU='".pnVarPrepForStore($ItemSKU)."' AND ItemID!='".pnVarPrepForStore($ItemID)."'";
    $result = $dbconn->Execute($sql);
    // Check for an error with the database code, and if so set an appropriate
    // error message and return
    if ($dbconn->ErrorNo() != 0) {
      pnSessionSetVar('errormsg', _PNC_GETFAILED);
      return false;
    }
    $rc = $result->RecordCount();
    $result->Close();
    return ($rc == 0);
}

/**
 * tests if all article parameters are correct
 * @param $args['ItemID'] int optional the ItemID
 * @param $args['ItemSKU']   string the ItemSKU (should be unique)
 * @param $args['ItemName'] string the name (short description) of the Item
 * @param $args['ItemCost'] float the itemcost without currency
 * @param $args['CategoryID'] int the corresponding category ID
 * @return '' if everything is ok
 * @return 'errors' (Array) with all errors (string) keys are from 0..
 * @return 'error_count' (int) number of errors >0 (if there are 0 errors, the Item entries are not set)
 */
function pncommerce_adminapi_ArticleValid($args)
{
    $errormsg = array();
    if ($args['ItemSKU'] =='')
    {
        $errormsg[] = _PNC_ITEMSKUMISSING;
    }
    if ($args['ItemName'] =='')
    {
        $errormsg[] = _PNC_ITEMNAMEMISSING;
    }
    if ($args['ItemCost'] =='')
    {
        $errormsg[] = _PNC_ITEMCOSTMISSING;
    }
    if ($args['CategoryID'] =='')
    {
        $errormsg[] = _PNC_ITEMCATEGORYMISSING;
    }
    if( ($args['ItemID']>0)&&!pncommerce_adminapi_ArticleSKUValid($args))
    {
      $errormsg[] = _PNC_DUPLICATEITEMSKU.": ".$args['ItemSKU'];
    }
    //prepare result, if error's occured
    if( count($errormsg) > 0 )
    {
        return $errormsg;
    }
    return true;
}

/**
 * tests if all image parameters are correct
 * @param $args['image']   Array (size,type,tmpname,name) the image
 * @param $args['imagetn'] Array (size,type,tmpname,name) the thumbnail optional needed when
 * @param $args['image_fname'] optional - filename of the image. (it is possible that it doesn't exist)
 * @return true if everything is ok
 * @return array with all errors (string) keys are from 0..
 */
function pncommerce_adminapi_ArticleImagesValid($args)
{
    $result = '';
    //ToDo:
    //- filesize taken from config
    //- test for valid images
    $errormsg = array();
    if (isset($args['image']))
    {
        if ($args['image']['size'] > 2048000)
        {
            $errormsg[] = _PNC_IMAGE_SIZE_ERROR;
        }
        if (!ereg("jpeg", $args['image']['type'])&&
            !ereg("jpg", $args['image']['type'])&&
            !ereg("bmp", $args['image']['type'])&&
            !ereg("gif", $args['image']['type'])&&
            !ereg("png", $args['image']['type']))
        {
            $errormsg[] = _PNC_IMAGE_TYPE_ERROR.": ".$args['image']['type'];
        }
    }
    if (isset($args['imagetn']))
    {
        if (!isset($args['image']) && !file_exists($args['image_fname']))
        {
            $errormsg[] = _PNC_IMAGE_TN_IMAGE_REQUIRED;
        }
        if ($args['imagetn']['size'] > 51200)
        {
            $errormsg[] = _PNC_IMAGE_TN_SIZE_ERROR;
        }
        if (!ereg("jpeg", $args['imagetn']['type'])&&
            !ereg("jpg", $args['imagetn']['type'])&&
            !ereg("bmp", $args['imagetn']['type'])&&
            !ereg("gif", $args['imagetn']['type'])&&
            !ereg("png", $args['imagetn']['type']))
        {
            $errormsg[] = _PNC_IMAGE_TN_TYPE_ERROR.": ".$args['imagetn']['type'];
        }
    }
    if( count($errormsg) > 0)
    {
        return $errormsg;
    }
    else
    {
        return $result;
    }
}

/**
 * process the uploaded images
 * create the thumbnails if needed
 * needs valid parameters. These should have been verified using the pncommerce_adminapi_ArticleImagesValid function
 * @param $args['itemID']  integer the ID of the corresponding item
 * @param $args['image']   Array (size,type,tmpname,name) the image
 * @param $args['imagetn'] Array (size,type,tmpname,name) the thumbnail optional needed when tngen=upload
 * @param $args['tnwidth'] int optional thumbnail width needed if create is selected
 * @param $args['tnheight'] int optional thumbnail height needed if create is selected
 * @param $args['imagefolder'] string optional the targetfolder for the images. product_images is used, is this parameter is empty.
 * @return true if everything is ok, otherwise false
 */
function pncommerce_adminapi_ArticleImagesStore($args)
{
    $Thumbnails = pncommerce_adminapi_getConfigThumbnail();
    extract($Thumbnails);

    pncloadapi('user', __FILE__, __LINE__);
    list($catID)=pnModAPIFunc('pncommerce','user','readfromdb', array('table' => 'items', 'fields' => array('category'), 'required' => array('itemid', $itemID)) );

    if (!pnSecAuthAction(0, 'pncommerce::category', "::".$catID, ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }

    if(!isset($args['imagefolder']))
    {
        $args['imagefolder']='product_images';
    }
    $imagedir = "modules/pncommerce/".$args['imagefolder'];
    $imagefile =$imagedir."/".$args['itemID'];
    $imagetnfile =$imagedir."/".$args['itemID']."tn";
    //Now get the filetype to use
    if (ereg("jpeg", $args['image']['type'])||
        ereg("jpg", $args['image']['type'])) $imagefile=$imagefile.".jpg";
    else if ( ereg("gif", $args['image']['type'])) $imagefile=$imagefile.".gif";
    else if (ereg("png", $args['image']['type'])) $imagefile=$imagefile.".png";
    else if (ereg("bmp", $args['image']['type'])) $imagefile=$imagefile.".bmp";
    else addlogmessage( _PNC_LOG_ADMINERROR, 'Unknown Imagetype: '.$args['image']['type'] );

    if (isset($args['imagetn']))
    {
        //tn is set, so we dont need to create
        //first we have to get rid of the old imageTN
        $oldimagetnfile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'thumbnail'=>true,'imagefolder'=>$args['imagefolder'])) ;
        while(file_exists($oldimagetnfile))
        {
            unlink($oldimagetnfile);
            $oldimagetnfile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'thumbnail'=>true, 'imagefolder'=>$args['imagefolder'])) ;
        }
        //Now get the filetype to use
        if (ereg("jpeg", $args['imagetn']['type'])||
            ereg("jpg", $args['imagetn']['type'])) $imagetnfile=$imagetnfile.".jpg";
        else if ( ereg("gif", $args['imagetn']['type'])) $imagetnfile=$imagetnfile.".gif";
        else if (ereg("png", $args['imagetn']['type'])) $imagetnfile=$imagetnfile.".png";
        else addlogmessage( _PNC_LOG_ADMINERROR, 'Unknown Imagetype: '.$args['imagetn']['type'] );
        move_uploaded_file($args['imagetn']['tmp_name'], $imagetnfile);
    }

    if ($args['image']['name'] != "")
    {
        // first we have to get rid of the old image
        // while is important here, because we don't know which extension the old image had and if someone uploaded a image by hand
        $oldimagefile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'imagefolder'=>$args['imagefolder'])) ;
        $AntiStaleCounter=10;
        while(file_exists($oldimagefile)&&($AntiStaleCounter>0))
        {
            unlink($oldimagefile);
            $oldimagefile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'imagefolder'=>$args['imagefolder'])) ;
            $AntiStaleCounter--;
        }
        if($AntiStaleCounter==0){
             addlogmessage( _PNC_LOG_ADMINERROR, 'infinite unlink loop detected and canceled in pncommerce_adminapi_ArticleImagesStore. Check your permissions!' );
        }
       // OK, now we can move it to the right place.
        move_uploaded_file($args['image']['tmp_name'], $imagefile);
    }

    $imagefile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'imagefolder'=>$args['imagefolder']));
    //  echo $imagefile."<br>";
    if (!isset($args['imagetn']) && file_exists($imagefile) &&
        isset($args['tnwidth']) && isset($args['tnheight']))
    {
        //TN not set we have to create, Now get the filetype to use
        if (ereg("jpeg", $imagefile)||
            ereg("jpg", $imagefile)) $imagetnfile=$imagetnfile.".jpg";
        else if ( ereg("gif", $imagefile)) $imagetnfile=$imagetnfile.".gif";
        else if (ereg("png", $imagefile)) $imagetnfile=$imagetnfile.".png";
        else if (ereg("bmp", $imagefile)) $imagetnfile=$imagetnfile.".bmp";
        $border = 0;
        //first we have to get rid of the old imageTN
        $oldimagetnfile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'thumbnail'=>true,'imagefolder'=>$args['imagefolder'])) ;
        $AntiStaleCounter=10;
        while(file_exists($oldimagetnfile)&&($AntiStaleCounter>0))
        {
            unlink($oldimagetnfile);
            $oldimagetnfile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'thumbnail'=>true, 'imagefolder'=>$args['imagefolder'])) ;
            $AntiStaleCounter--;
        }
        if($AntiStaleCounter==0){
             addlogmessage( _PNC_LOG_ADMINERROR, 'infinite unlink loop detected and canceled in pncommerce_adminapi_ArticleImagesStore. Check your permissions!' );
        }

        if ($TNCreateMethod == "im")
        {
            // changed as suggested by tduarte
            system("$TNIMPath/convert -quality 80 -antialias -resize ".
                    $args['tnwidth']."x".$args['tnheight'].
                    " '$imagefile' '$imagetnfile' 2>&1");
/*
            system( "$TNIMPath/convert -quality 80 -antialias -sample ".
                    $args['tnwidth']."x".$args['tnheight'].
                    " -bordercolor black -border 0 \"$imagefile\" \"$imagetnfile\" 2>&1");
*/
        }
        else if ($TNCreateMethod == "gd")
        {
            $imageInfo = getimagesize($imagefile);
            $width = $imageInfo[0];
            $height = $imageInfo[1];
            if (ereg("jpeg", $imagefile)||
                ereg("jpg", $imagefile)) $im = ImageCreateFromJPEG($imagefile);
            else if ( ereg("gif", $imagefile)) $im = ImageCreateFromGIF($imagefile);
            else if (ereg("png", $imagefile)) $im = ImageCreateFromPNG($imagefile);

        $tn = ImageCreate($args['tnwidth'], $args['tnheight']);
        ImageCopyResized($tn, $im, 0, 0, 0, 0, $args['tnwidth'],$args['tnheight'], $width, $height);
        if (ereg("jpeg", $imagefile)||
            ereg("jpg", $imagefile)) ImageJPEG($tn, $imagetnfile, 75);
        else if ( ereg("gif", $imagefile)) ImageGIF($tn, $imagetnfile, 75);
        else if (ereg("png", $imagefile)) ImagePNG($tn, $imagetnfile, 75);

        }
    }
    return true;
}

/**
 * process the uploaded images
 * @param $args['itemID']  integer the ID of the corresponding item
 * @param $args['delimage'] bool ('true' or 'false') image and thumbnail will be deleted, if 'true'
 * @param $args['delimagetn'] bool ('true' or 'false') thumbnail will be deleted, if 'true'
 * @param $args['imagefolder'] string optional the targetfolder for the images. product_images is used, is this parameter is empty.
 * @return true if everything is ok, otherwise false
 */
function pncommerce_adminapi_ArticleImagesRemove($args)
{
  if(!isset($args['imagefolder']))$args['imagefolder']='product_images';
  $Thumbnails = pncommerce_adminapi_getConfigThumbnail();
  extract($Thumbnails);
    pncloadapi('user', __FILE__, __LINE__);
  list($catID)=pnModAPIFunc('pncommerce','user','readfromdb', array('table' => 'items', 'fields' => array('category'), 'required' => array('itemid', $itemID)) );

  $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$catID));
  if (!pnSecAuthAction(0,
                       'pncommerce::category',
                       $CName."::".$catID,
                       ACCESS_EDIT)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }


  $imagefile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'imagefolder'=>$args['imagefolder'])) ;
  $imagetnfile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'thumbnail'=>true, 'imagefolder'=>$args['imagefolder'])) ;

  while(($args['delimagetn'] == 'true') && file_exists($imagetnfile)) {
    unlink($imagetnfile);
    $imagetnfile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'thumbnail'=>true, 'imagefolder'=>$args['imagefolder'])) ;
  }
  while (($args['delimage'] == 'true') && file_exists($imagefile)) {
    unlink($imagefile);
    $imagefile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'imagefolder'=>$args['imagefolder'])) ;
    //we don't allow thumbnails without images
    while(($args['delimagetn'] == 'true') && file_exists($imagetnfile)) {
      unlink($imagetnfile);
      $imagetnfile=pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $args['itemID'], 'thumbnail'=>true, 'imagefolder'=>$args['imagefolder'])) ;
    }
  }
  return true;
}

/**
 * generate a list of available categories
 *********************************************
 ********************************************* THIS FUNCTION IS OBSOLET WHEN THE SMARTIFICATION IS FINISHED!
 *********************************************
 *********************************************
  WHY? (fs)
  Because we should read the list in the template and set the checked flag there too [Sourcecode-chat *g*] (PC)
 * @return array the output is formatted for dropdown lists
 * @param $args['selected']  selected item
 * @param $args['NoParentCategoryOption']  bool yes: add an option for "no parent category"
 */
function pncommerce_adminapi_categorylist($args)
{
    extract($args);

    pncloadapi('user', __FILE__, __LINE__);
      $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                              array('sql' => "SELECT CategoryID, Category, CatParent FROM ".pnConfigGetVar('prefix')."_pncommerce_category"));
    $num_items = 0;
    if ($result != false)
    {
        $num_items = count ($result);
        $count = 0;

        foreach ($result as $resultline)
        {
            list($CID, $Cat, $CPa) = $resultline;
            // $at may be a serialized array
            list( $CatTree, $dummy ) = extractNameAndSequence( $Cat );
            $catlist0[$count] = $CID;
            $CPaP = $CPa;
            if ($CPaP)
            {
                while ($CPaP)
                {
                    $result2 = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                                               array('sql' => "SELECT Category, CatParent FROM ".
                                                 pnConfigGetVar('prefix')."_pncommerce_category WHERE CategoryID='".(int)$CPaP."'"));
                    if ($result2 != false) list($CPaN, $CPaP) = $result2[0];
                    else{ $CPaP=''; $CPaN = ''; }
                    list( $cnametemp, $dummy ) = extractNameAndSequence( $CPaN );
                    $CatTree = $cnametemp." > ".$CatTree;
                }
            }
            else
            {
                list( $CatTree, $dummy ) = extractNameAndSequence( $Cat );
            }
            $catlist1[$count] = $CatTree;
            $count++;
        }

        if ($catlist1)
        {
            array_multisort($catlist1, SORT_STRING, SORT_ASC, $catlist0);
        }

        $count = 0;
        $selectflag = false;
        while ($catlist0[$count])
        {
            if ($selected == $catlist0[$count])
            {
                $sel_string = "selected";
                $selectflag = true;
            }
            else
            {
                $sel_string = "";
            }
            $cat_list .= "<option value=\"$catlist0[$count]\" $sel_string> $catlist1[$count] </option>\n";
            $count++;
        }
        if( $NoParentCategoryOption == true )
        {
            // reset sel_string for next use
            $sel_string = "";
            if( $selectflag == false )
            {
                // nothing selected
                $sel_string = "selected";
            }
            $cat_list = "<option value='' $sel_string >"._PNC_NOPARENTCATEGORY."</option>\n".$cat_list;
        }
        $cat_array = array($cat_list, $num_items);
        return $cat_array;
    }
    return false;
}

/*
 * readAllCategoriesForSelect
 *
 *@param $args['SelectedCategory'] int
 *returns array of categories
 */
function pncommerce_adminapi_readAllCategoriesForSelect( $args )
{
    $categories = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                                array('sql' => "SELECT CategoryID, Category FROM ".pnConfigGetVar('prefix')."_pncommerce_category ORDER BY CategoryID ASC"));
    if( $categories <> false )
    {

        $preselect[$args['SelectedCategory']] = "selected";
        foreach( $categories as $category )
        {
            list( $catid, $catname ) = $category;
            $catlist .= "<option value='$catid' ".$preselect[$catid]." >$catname</option>\n";
        }
        return $catlist;
    }
    return false;
}

/**
 * generate a list of available categories
 * @return array of existing categories Format: array[CategoryID]='Categoryname(+path)'
 *
 *
 * PLEASE USE pncommerce_userapi_readCategoryList - THIS PROVIDES MORE INFORMATION !!
 */
function pncommerce_adminapi_getCategorylist()
{
    echo "Please use pncommerce_userapi_readCategoryList instead of pncommere_adminapi_getCategoryList!!!";

  if (!pnSecAuthAction(0,
                       'pncommerce::category',
                       "::".$catID,
                       ACCESS_OVERVIEW)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }
    pncloadapi('user', __FILE__, __LINE__);
  $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                          array('sql' => "SELECT CategoryID, Category, CatParent FROM ".pnConfigGetVar('prefix')."_pncommerce_category"));
  $num_items = 0;
  if ($result != false)
    {
      $num_items = count ($result);
      $count = 0;

      foreach ($result as $resultline)
        {
          list($CID, $Cat, $CPa) = $resultline;
          $CatTree = $Cat;
          $catlist0[$count] = $CID;
          $CPaP = $CPa;
          if ($CPaP)
            {
              while ($CPaP)
                {
                  $result2 = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                                           array('sql' => "SELECT Category, CatParent FROM ".
                                                 pnConfigGetVar('prefix')."_pncommerce_category WHERE CategoryID='".(int)$CPaP."'"));
                  if ($result2 != false) list($CPaN, $CPaP) = $result2[0];
                  else{ $CPaP=''; $CPaN = ''; }
                  $CatTree = $CPaN." > ".$CatTree;
                }
            }
          else
            {
              $CatTree = $Cat;
            }
          $catlist1[$CID] = $CatTree;
          $count++;
        }

      if ($catlist1)
      {
          array_multisort($catlist1, SORT_STRING, SORT_ASC, $catlist0);
      }
//echo "<pre>";
//print_r($catlist1);
//echo "</pre>";

      return $catlist1;
    }
  return false;
}

/**
 * generate a list of available items
 * @return array the output is formatted for dropdown lists
 **/

function pncommerce_adminapi_itemlist()
{
  //We shouldn't do this here. All visualization should be made in the templates
  echo "is this called? pncommerce_adminapi_itemlist<br>";
  if (!pnSecAuthAction(0,
                       'pncommerce::',
                       "::",
                       ACCESS_OVERVIEW)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }
    pncloadapi('user', __FILE__, __LINE__);
  $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                          array('sql' => "SELECT ItemID, ItemName, ItemSKU FROM ".pnConfigGetVar('prefix')."_pncommerce_items WHERE ItemSKU REGEXP \"^[^\%]\" ORDER BY ItemName"));
  $num_items = 0;

  if ($result != false)
    {
      $num_items = count($result);
      foreach ($result as $resultline)
        {
          list ($IID, $INa, $ISK) = $resultline;
          $item_list = $item_list."<OPTION VALUE=\"$IID\"> $INa - $ISK </OPTION>";
        }
      $list_array = array($item_list, $num_items);
      return $list_array;
    }
  return false;
}

/**
 * tests if all category parameters are correct
 * @param $args['Category']   The name of the category
 * @param $args['CategoryID']   The ID of the category
 * @param $args['CategorySequence']   The sequence number of the category
 * @param $args['ShipMethod']   The Shippingmethod of the category
 * @param $args['CategoryParent']   The parent category of the category
 * @param $args['CategoryInvisible']   The visibillity property of the category
 * @returns true or Array
 * @return true if everything is ok
 * @return 'errors' (Array) with all errors (string) keys are from 0..
 */
function pncommerce_adminapi_CategoryValid($args)
{
    $errormsg = array();
    pncloadapi('user', __FILE__, __LINE__);

    if( !is_numeric($args['CategorySequence']) )
    {
        $errormsg[] = ""._PNC_CATERRORINVALIDSEQUENCEFORMAT;
    }
    if (isset($args['Category'])&&$args['Category']!='')
    {
        //rbonte@choicenet.ne.jp: This is incompatible with non latin scripts.
        /*
        if(!ereg("[a-zA-Z0-9]",$args['Category']))
        {
            $errormsg[] = ""._PNC_CATERRORNAMEDIGITS;
        }
        */
        if($args['CategoryID']AND ($args['CategoryID'] == $args['CategoryParent']))
        {
            $errormsg[] = ""._PNC_CATNAMECANNOTEQUALPARENT;
        }
        $query = "SELECT Category FROM ".pnConfigGetVar('prefix')."_pncommerce_category
                 WHERE Category='".$args['Category']."'
                 and CatParent= '".$args['CategoryParent']."' ";
        if ( $args['CategoryID'] )
        {
            $query=$query." and CategoryID!='".$args['CategoryID']."'";
        }
        $num = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBnumrowspreformat',array( 'sql' => $query));
        if($num>0)
        {
            $errormsg[] = ""._PNC_DUPLICATECAT;
        }
    }
    else
    {
        $errormsg[]= ""._PNC_CATNAMEMISSING;
    }
    if( count($errormsg) > 0 )
    {
        return $errormsg;
    }
    else
    {
        return true;
    }
}

/**
 * Deletes a category in the database and the coresponding thumbnails and images
 * All subcategories are removed too (recursivly)
 * !! ALL ITEMS THAT BELONG TO THE CATEGORY OR ITS SUBCATEGORIES !!
 * !! WILL BE DELETED TOO !!
 * !! (OR YOU SET THE AltCategoryID AND THE CORRESPONDING BOOL FIELDS) !!
 * Important: This will produce a infinite loop, when there are cyclic references between cat's!
 * @param $args['CategoryID'] int the category that will be removed
 * @param $args['AltCategoryID'] int optional the alternative category that will used as parent cat. instead of the one that will be deleted
 * @param $args['SubCategories'] bool optional if true then use AltCategoryID for direct subcategories as parent
 * @param $args['Items'] bool optional if true then use AltCategoryID as category for all items if the category
 * @returns '' or string
 * @return '' when everything is ok
 * @return errordescription if something bad happens
 */
function pncommerce_adminapi_CategoryDelete($args)
{
  extract($args);
    pncloadapi('user', __FILE__, __LINE__);
  $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$catID));
  if (!pnSecAuthAction(0,
                       'pncommerce::category',
                       $CName."::".$catID,
                       ACCESS_DELETE)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }

  if($CategoryID=='')return _PNC_NOCATGGIVEN;
  //First get a list of all child categories
  $subcatresult = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                                array( 'sql' => "SELECT CategoryID FROM ".
                                       pnConfigGetVar('prefix')."_pncommerce_category WHERE CatParent='".(int)$CategoryID."'"));
  $num = 0;
  if ($subcatresult != false){
    $num = count ($subcatresult);
  }
  if ( $num ) {
    //OK, we found some subcategories. We have to delete/move them first.
    if(isset($SubCategories)&&($SubCategories==true) && isset($AltCategoryID)){
      //OK, move them
      foreach ( $subcatresult as $subcatresultline){
        //to propagate all parameters to the subcalls...
        list ( $subcatID ) = $subcatresultline;
        $sql = "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_category SET
                CatParent='".(int)pnVarPrepForStore($args['AltCategoryID'])."' WHERE CategoryID='".(int)pnVarPrepForStore($subcatID)."'";
        pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat', array( 'sql' => $sql));
      }
    }else{
      //delete them
      foreach ( $subcatresult as $subcatresultline){
        list ( $subcatID ) = $subcatresultline;
        //to propagate all parameters to the subcalls...
        $recArg=$args;
        $recArg['CategoryID']=$subcatID;
        pncommerce_adminapi_CategoryDelete($recArg);
      }
    }
  }

  //Now we're deleting/moving the items from this category
  $Query = "SELECT ItemID FROM ".pnConfigGetVar('prefix')."_pncommerce_items WHERE Category='".(int)$CategoryID."'";
  $itemresult = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat', array( 'sql' => $Query));
  $num = 0;
  if ($itemresult != false){
    $num = count ($itemresult);
  }
  if ( $num ) {
    //OK, we found some items
    if($Items==true && isset($AltCategoryID)){
      foreach ( $itemresult as $itemresultline){
        list ( $ItemID ) = $itemresultline;
        $sql = "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_items SET
                Category='".(int)pnVarPrepForStore($args['AltCategoryID'])."' WHERE ItemID='".(int)pnVarPrepForStore($ItemID)."'";
        pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat', array( 'sql' => $sql));
      }
    }else{
      foreach ( $itemresult as $itemresultline){
        list ( $ItemID ) = $itemresultline;
        //echo "Remove item -$itemresultline[0]- ";print_r($itemresultline);echo "<br>";
        pncommerce_adminapi_ArticleDelete(Array('ItemID'=>$ItemID));
      }
    }
  }
  //All cleaned up. Delete the Category.
  $Query = "DELETE FROM ".pnConfigGetVar('prefix')."_pncommerce_category WHERE CategoryID='".(int)pnVarPrepForStore($args['CategoryID'])."'";
  pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat', array( 'sql' => $Query));

  return true;
}

/**
 * Store an category in the database
 * The category must exist!
 * (Otherwise use add!)
 * @param $args['Category']   The name of the category
 * @param $args['CategoryID']   The ID of the category
 * @param $args['CategorySequence']   The sequence number of the category
 * @param $args['CategoryParent']   The parent category of the category
 * @param $args['CategoryInvisible']   The visibillity property of the category
 * @param $args['VATID']  [1..9] the VAT ID
 * @param $args['CatIntroTemplateID']   CategoryIntro TemplateID
 * @param $args['ItemListTemplateID']   ItemList TemplateID
 * @param $args['ItemViewTemplateID']   ItemView TemplateID
 */

function pncommerce_adminapi_CategoryStore($args)
{
    pncloadapi('user', __FILE__, __LINE__);
    if (!pnSecAuthAction(0,
                       'pncommerce::category',
                       $args['Category']."::".$args['CategoryID'],
                       ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }

    extract($args);

    // special hack: Save the category sequence and name as an serialized array
    $c_hack = serialize( array( 'sequence' => $CategorySequence,
                                'name'     => $Category ) );

    $sql = "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_category
                            SET Category='".pnVarPrepForStore($c_hack)."', CatParent='".pnVarPrepForStore($CategoryParent)."',
                            CatInvisible='".pnVarPrepForStore($CategoryInvisible)."',
                            VATID='".pnVarPrepForStore($VATID)."',CatIntroTemplateID='".pnVarPrepForStore($CatIntroTemplateID)."',
                            ItemListTemplateID='".pnVarPrepForStore($ItemListTemplateID)."', ItemViewTemplateID='".pnVarPrepForStore($ItemViewTemplateID)."'
                            WHERE CategoryID='".(int)pnVarPrepForStore($CategoryID)."'";
    pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat', array( 'sql' => $sql));

    $query="SELECT Category FROM ".pnConfigGetVar('prefix')."_pncommerce_category WHERE CategoryID='".(int)pnVarPrepForStore($CategoryID)."'";
    list($OldCat) = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat', array( 'sql' => $Query));
    return true;
}

/**
 * Add an category in the database
 * @param $args['Category']   The name of the category
 * @param $args['CategoryParent']   The parent category of the category
 * @param $args['VATID']  [1..9] the VAT ID
 * @param $args['CategoryInvisible']   The visibillity property of the category
 * @returns int or bool
 * @return 'CategoryID'    int The ID of the category
 * @return false if an error occured
 */
function pncommerce_adminapi_CategoryAdd($args)
{
  extract($args);
  if (!pnSecAuthAction(0,
                       'pncommerce::category',
                       $args['Category']."::".$args['CategoryID'],
                       ACCESS_ADD)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

  }

  list($dbconn) = pnDBGetConn();
  $CategoryTable = pnConfigGetVar('prefix').'_pncommerce_category';

  $sql = "INSERT INTO $CategoryTable (Category) VALUES ('".pnVarPrepForStore($Category)."')";
  $dbconn->Execute($sql);
  // Check for an error with the database code, and if so set an appropriate
  // error message and return
  if ($dbconn->ErrorNo() != 0) {
    pnSessionSetVar('errormsg', _PNC_GETFAILED);
    return false;
  }
  //Now we fetch the ID to store all of the data
  //No error checking needed, because the prior action was a success
  $args['CategoryID'] = $dbconn->PO_Insert_ID($CategoryTable, 'CategoryID');
  //Why the effort?
  //So we have to maintain only one function for new fields
  pncommerce_adminapi_CategoryStore($args);
  return $args;

  return true;
}

/*
 * Read the template list based on parameters and build the <option></option> for selects
 * @param $args['TypeOnly'] The type of template to read, if empty all templates will be read
 * @param $args['recentTemplate'] the recent template. Makes only sense when $TypeOnly is
 *                                supplied also. Marks this template as selected
 * @returns string with HTML code or false on error
 */
function pncommerce_adminapi_readtemplatelist($args)
{
    extract ($args);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0,
                       'pncommerce::',
                       "::",
                       ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }

    $readsql = "SELECT TemplateID, TemplateDesc, TemplateType FROM ".pnConfigGetVar('prefix')."_pncommerce_templates";
    if ( $TypeOnly > 0 )
    {
        $readsql .= " WHERE TemplateType=".(int)pnVarPrepForStore($TypeOnly);
    }
    else
    {
        $readsql .= " ORDER BY TemplateType";
    }
    $result = pnModAPIFunc ( 'pncommerce', 'user', 'readfromDBpreformat',
                               array( 'sql' => $readsql ));

    if ($result != false)
    {
        $ttypearray = array( '',
                           pnVarPrepForDisplay(_PNC_TEMPLATETYPE_1),
                           pnVarPrepForDisplay(_PNC_TEMPLATETYPE_2),
                           '',
                           pnVarPrepForDisplay(_PNC_TEMPLATETYPE_4),
                           pnVarPrepForDisplay(_PNC_TEMPLATETYPE_5),
                           '',
                           '',
                           '',
                           pnVarPrepForDisplay(_PNC_TEMPLATETYPE_9),
                           pnVarPrepForDisplay(_PNC_TEMPLATETYPE_10));
        $temp_list = "";

        foreach ($result as $resultline)
        {
            list( $tid, $tdesc, $ttype ) = $resultline;
            if ( $tid == $recentTemplate)
            {
                $temp_list .= sprintf( "<option value=%d selected>%s (%s)</option>\n", $tid, $tdesc, $ttypearray[$ttype]);
            }
            else
            {
                $temp_list .= sprintf( "<option value=%d>%s (%s)</option>\n", $tid, $tdesc, $ttypearray[$ttype]);
            }

        }
        return $temp_list;
    }
    return false;
}

/*
 * Read the list of vat ids and builds the <option></option> for selects
 * @param $args['recentVATID'] the recent Vat ID. Marks this ID as selected
 * @returns string with HTML code or false on error
 */
function pncommerce_adminapi_readVATList($args)
{
    extract ($args);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::', "::", ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }

    if( $recentVATID == 0 )
    {
        $vatlist .= "<option value=0 selected >"._PNC_INHERITEDVAT."</option>";
    }
    else
    {
        $vatlist .= "<option value=0 >"._PNC_INHERITEDVAT."</option>";
    }

    for($i=1;$i<=9;$i++)
    {
        $vat = pnModGetVar( 'pncommerce', 'VATID'.$i );
        if( !$vat )
        {
            $vat = _PNC_NOVATSET;
        }
        else
        {
            $vat .= "%";
        }
        if( $recentVATID == $i )
        {
            $vatlist .= "<option value=$i selected >$vat (ID $i)</option>";
        }
        else
        {
            $vatlist .= "<option value=$i >$vat (ID $i)</option>";
        }
    }
    return $vatlist;
}

/**
 * set the VAT percentage to a given ID
 * to save 16% VAT set VAT to 16
 * 0 disables this VATID
 * the get function is located in the userapi
 * @param $args['VATID'] int 1..9
 * @param $args['VAT'] int >=0
 */
function pncommerce_adminapi_setVAT($args){
  extract($args);
  if(($VATID<1)or($VATID>9)or($VAT<0))return false;
  return pnModSetVar('pncommerce','VATID'.$VATID,$VAT);
}


/**
 * returns category tree with all necessary informations for one category (all categories below)
 * this function works recursively and may abort when the amount of categories is too big (10000+x) depending on the server settings
 * @param args['startCatID'] ID of the category to start with
 * @return Array
 * @returns Array of arrays each has all fields declared in the category table + subItems (an array with all subcategories, maybe an empty array)
 */
function pncommerce_adminapi_getSingleCategoryTree($args)
{
    pncloadapi('user', __FILE__, __LINE__);

    $result=array();
    //first find all top level categories
    $sql="SELECT CategoryID,Category,CatParent,VATID,CatInvisible FROM ".pnConfigGetVar('prefix')."_pncommerce_category WHERE CatParent=\"".pnVarPrepForStore($args['startCatID'])."\" AND CatInvisible <> 'on' ORDER BY CategoryID;";
    $startcat= pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',array( 'sql' => $sql));
    $fields=array('CategoryID','Category','CatParent','VATID','CatInvisible');

    if($startcat!=false)
    {
        foreach ($startcat as $cat)
        {
            //the array we get has numbers instead of names, we change that here
            $namedCat=array();
            foreach ($cat as $key=>$tmp)
            {
                if( $fields[$key] == 'Category' )
                {
                    list( $namedCat[$fields[$key]], $dummy ) = extractNameAndSequence( $tmp );
                }
                else
                {
                    $namedCat[$fields[$key]]= $tmp;
                }
            }
            // get the template ids and names used
            $namedCat['CatIntroTemplateID'] = pnModAPIFunc('pncommerce','user','GetTemplateID', array( 'CID' => $namedCat['CategoryID'], 'TemplateType' => 'CatIntroTemplateID'));
            $namedCat['ItemViewTemplateID'] = pnModAPIFunc('pncommerce','user','GetTemplateID', array( 'CID' => $namedCat['CategoryID'], 'TemplateType' => 'ItemViewTemplateID'));
            $namedCat['CatIntroTemplateDesc'] = pnModAPIFunc('pncommerce','user','getTemplateByID', array( 'TemplateID' => $namedCat['CatIntroTemplateID'], 'DescOnly' => true));
            $namedCat['ItemViewTemplateDesc'] = pnModAPIFunc('pncommerce','user','getTemplateByID', array( 'TemplateID' => $namedCat['ItemViewTemplateID'], 'DescOnly' => true));
            //We provide all properties! be careful with that!
            $result[$cat['0']]=$namedCat;
            $result[$cat['0']]['subItems']=pncommerce_adminapi_getSingleCategoryTree(array('startCatID'=>$namedCat['CategoryID']));
        }
	usort($result, "name_cmp");
    }
    return $result;
}

function name_cmp($a, $b)
{
	if ($a["Category"] == $b["Category"]) {
	        return 0;
	}
    	return ($a["Category"] < $b["Category"]) ? -1 : 1;
}

/**
 * returns category tree with all necessary informations
 * @return Array
 * @returns Array of arrays each has all fields declared in the category table + subItems (an array with all subcategories, maybe an empty array)
 */
function pncommerce_adminapi_getCategoryTree($args)
{
    return  pncommerce_adminapi_getSingleCategoryTree(array('startCatID'=>''));
}

/**
 * count the number of orders
 * @return number of orders
 */
function pncommerce_adminapi_countorders()
{
    list($dbconn) = pnDBGetConn();
    $pntable = pnDBGetTables();
    $table = $pntable['pncommerce_orders'];
    $column = &$pntable['pncommerce_orders_column'];
    $sql = "SELECT COUNT(1) FROM $table";
    $result = $dbconn->Execute($sql);
    if ($dbconn->ErrorNo() != 0) {
        return false;
    }
    list($numitems) = $result->fields;
    $result->Close();
    return $numitems;
}
/**
 * count the number of users
 * @return number of users
 */
function pncommerce_adminapi_countusers()
{
    list($dbconn) = pnDBGetConn();
    $pntable = pnDBGetTables();
    $table = $pntable['pncommerce_orders'];
    $column = &$pntable['pncommerce_orders_column'];
    $sql = "SELECT $column[UserID] FROM $table GROUP BY $column[UserID]";
    $result = $dbconn->Execute($sql);
    if ($dbconn->ErrorNo() != 0) {
        return false;
    }
        $numitems = count ($result);
    $result->Close();
    return $numitems;
}
/**
 *  extract order infos
 * param args['starttime'] optional
 * param args['endtime'] optional necessary when starttime is set
 * return @orderinfos(array)
 */
function pncommerce_adminapi_getcartdata($args)
{
   extract($args);
   //starttime, $endtime
    pncloadapi('user', __FILE__, __LINE__);
     if (!pnSecAuthAction(0, 'pncommerce::', "::", ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
   list($dbconn) = pnDBGetConn();
    $pntable = pnDBGetTables();
    $table = $pntable['pncommerce_orders'];
    $column = &$pntable['pncommerce_orders_column'];
    $sql = "SELECT $column[OrderNumber] FROM $table";
     if ($starttime!="")
         {
         $sql.=" WHERE $column[Date]>".pnVarPrepForStore($starttime)." AND $column[Date]<".pnVarPrepForStore($endtime);
         }
    $result = $dbconn->Execute($sql);
    if ($dbconn->ErrorNo() != 0) {
        return false;
    }
    $Order=array();
    for (; !$result->EOF; $result->MoveNext())
    {
        list( $number) = $result->fields;
        $Order[] = pnModApiFunc('pncommerce','user','getOrder',Array('ON'=>$number));
    }
    $result->Close();

    return $Order;
}

/**
 * Extract the order infos
 *
 * @param args['Report'] Report that should be updated
 * @param args['Order'] Order to process
 * @returns updated report array
 */
function pncommerce_adminapi_updateReport($args)
{
    extract($args);
    if($Report=='Empty')
    {
        $Report=array('Total'=>0,
                            'VAT'=>array(),
                            'NetTotal'=>0,
                            'ShipMethod'=>array(),
                            'PayMethod'=>array(),
                            'OrderCount'=>0,
                            'UserCount'=>0,
                            'UserList'=>array(),
                            'ItemCount'=>0,
                            'QuantityCount'=>0,
                            'FinalMod'=>Array()
                            );
    }
    if(!isset($Order)) return $Report;
    //First the Item related stuff:
    foreach ($Order['CartData']['Items'] as $item)
    {
        //If item is no array, take next, something went wrong
        if (!is_array($item))break;
        $Report['QuantityCount']+=$item['ItemQuantity'];
        $Report['ItemCount']++;
    }//Items foreach

    //After that the Order related stuff
    $Report['OrderCount']++;
    $Report['Total']+=$Order['CartData']['Total'];
    $Report['NetTotal']+=$Order['CartData']['SubTotal'];
//echo "<pre>";print_r($Order);echo "</pre>";
    foreach($Order['CartData']['VATList'] as $VAT=>$VATAmount)
    {
        $Report['VAT'][$VAT]+=$VATAmount;
    }

    if(empty($Report['PayMethod'][$Order['UserData']['PayMethod']]))
    {
        $Report['PayMethod'][$Order['UserData']['PayMethod']]=1;
    }
    else
    {
        $Report['PayMethod'][$Order['UserData']['PayMethod']]++;
    }

    if(empty($Report['ShipMethod'][$Order['UserData']['ShipMethod']]))
    {
        $Report['ShipMethod'][$Order['UserData']['ShipMethod']]=1;
    }
    else
    {
        $Report['ShipMethod'][$Order['UserData']['ShipMethod']]++;
    }
    if(!empty($Order['FinalMod']))
    {
        if(empty($Report['FinalMod'][$Order['FinalMod']]))
        {
            $Report['FinalMod'][$Order['FinalMod']]=1;
        }
        else
        {
            $Report['FinalMod'][$Order['FinalMod']]++;
        }
    }
    if(isset($Report['UserList'][$Order['UserData']['KID']]))$Report['UserList'][$Order['UserData']['KID']]++;
    else $Report['UserList'][$Order['UserData']['KID']]=1;

    $Report['UserCount']=count($Report['UserList']);
    return $Report;
}

/**
 * Extract the order infos
 * @param $args['Orders'] optional an array of orders, all available orders are used if not set
 * @return $array['all']   report of all orders
 * @return $array['month']  report of all orders this month
 * @return $array['year']   report of all orders this year
 * @return $array['months']   report of all orders listed as monthly reports (Array[1..12])
 */
function pncommerce_adminapi_calculateBasicStats($args)
{
    if (is_array($args))
    {
        extract($args);
    }
    if(!$Orders)$orderlist=pncommerce_adminapi_getcartdata($starttime, $endtime);
    else $orderlist=$Orders;
    //When no result is found, return nothing:
    if (!is_array($orderlist))return array();

    //prepare ranges for discrete stats
    $now=time();
    $month=date("n", $now);
    $year=date("Y", $now);
    $yearstart=mktime(0,0,0,0,0,$year);
    $yearend=mktime(0,0,0,0,0,$year+1);

    $months=array();
    for($i=1;$i<=12;$i++){
        $months[$i]=array('start'=>mktime(0,0,0,$i,0,$year), 'end'=>mktime(0,0,0,$i+1,0,$year));
    }

    //Initialise with empty, the array get's prepared on the first updateReport
    $monthsReport=Array();
    for($i=1;$i<=12;$i++){
        $monthsReport[$i]='Empty';
    }
    $yearReport='Empty';
    $allReport='Empty';

//        echo "<pre>";print_r($orderlist);echo "</pre>";

    foreach ($orderlist as $order)
    {
        //If order is no array, take next, something went wrong
//        if (!is_array($order)){break;}
//        else echo "Order is no array! :$order:<br><br>";

        $allReport=pnModApiFunc('pncommerce','admin','updateReport',array('Report'=>$allReport,'Order'=>$order));

        if (($yearstart<$order['Date'])&&($yearend>$order['Date']))
        {
            $yearReport=pnModApiFunc('pncommerce','admin','updateReport',array('Report'=>$yearReport,'Order'=>$order));
        }
        else
        if($yearReport=='Empty'){
            $yearReport=pnModApiFunc('pncommerce','admin','updateReport',array('Report'=>$yearReport));
        }


        for($i=1;$i<=12;$i++)
        {
            if (($months[$i]['start']<$order['Date'])&&($months[$i]['end']>$order['Date']))
            {
                $monthsReport[$i]=pnModApiFunc('pncommerce','admin','updateReport',array('Report'=>$monthsReport[$i],'Order'=>$order));
            }
            else
            if($monthsReport[$i]=='Empty'){
                $monthsReport[$i]=pnModApiFunc('pncommerce','admin','updateReport',array('Report'=>$monthsReport[$i]));
            }
        }
    }
    $allReport['Description']=pnVarPrepForDisplay(_PNC_STATISTICSALL);
    $yearReport['Description']=pnVarPrepForDisplay(_PNC_STATISTICSYEAR);
    $monthReport=$monthsReport[$month];
    $monthReport['Description']=pnVarPrepForDisplay(_PNC_STATISTICSMONTH);
    $monthsReports['Reports']=$monthsReport;
    $monthsReports['Description']=pnVarPrepForDisplay(_PNC_STATISTICSMONTHS);
    $monthsReports['Type']='Multi';
    $monthsReports['Reports']['1']['Description']=pnVarPrepForDisplay(_PNC_JANUARY);
    $monthsReports['Reports']['2']['Description']=pnVarPrepForDisplay(_PNC_FEBRUARY);
    $monthsReports['Reports']['3']['Description']=pnVarPrepForDisplay(_PNC_MARCH);
    $monthsReports['Reports']['4']['Description']=pnVarPrepForDisplay(_PNC_APRIL);
    $monthsReports['Reports']['5']['Description']=pnVarPrepForDisplay(_PNC_MAY);
    $monthsReports['Reports']['6']['Description']=pnVarPrepForDisplay(_PNC_JUNE);
    $monthsReports['Reports']['7']['Description']=pnVarPrepForDisplay(_PNC_JULY);
    $monthsReports['Reports']['8']['Description']=pnVarPrepForDisplay(_PNC_AUGUST);
    $monthsReports['Reports']['9']['Description']=pnVarPrepForDisplay(_PNC_SEPTEMBER);
    $monthsReports['Reports']['10']['Description']=pnVarPrepForDisplay(_PNC_OCTOBER);
    $monthsReports['Reports']['11']['Description']=pnVarPrepForDisplay(_PNC_NOVEMBER);
    $monthsReports['Reports']['12']['Description']=pnVarPrepForDisplay(_PNC_DECEMBER);
    $result=Array('all'=>$allReport,'month'=>$monthReport,'year'=>$yearReport,'months'=>$monthsReports);
//    echo "<pre>";print_r($result);echo "</pre>";
    return $result;
}


/**
 * cextract order infos
 * return @orderinfos(array)
 */
function pncommerce_adminapi_getcartdata_user($args)
{
        extract($args);
        if (!isset($userid)){$userid=3;}
    list($dbconn) = pnDBGetConn();
    $pntable = pnDBGetTables();
    $table = $pntable['pncommerce_orders'];
    $column = &$pntable['pncommerce_orders_column'];
    $sql = "SELECT $column[CartData], $column[Date] FROM $table WHERE $column[UserID]='".pnVarPrepForStore($userid)."'";
    $result = $dbconn->Execute($sql);
    if ($dbconn->ErrorNo() != 0) {
        return false;
    }
        $Order=array();
        $i=0;
        for (; !$result->EOF; $result->MoveNext())
            {
                        list($cartdata, $date) = $result->fields;
                        $Order[$i]['cart'] = unserialize( stripslashes( $cartdata ) );
                        $Order[$i]['date']=$date;
                        $i++;
                        }
    $result->Close();
    return $Order;
}

/*
 * buildCategoryTreeForSelect
 *
 *@param $args['ParentID']
 *@returns the path to a category as <options selected></options> for a select statement
 *         or alse on error
 */
function pncommerce_adminapi_buildCategoryTreeForSelect( $args )
{
    extract( $args );
    pncloadapi('user', __FILE__, __LINE__);

    if ( $ParentID )
    {
        $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                                array( 'sql' => "SELECT Category,CatParent FROM ".pnConfigGetVar('prefix')."_pncommerce_category WHERE CategoryID='".(int)pnVarPrepForStore($ParentID)."'"));
        if( $result!=false )
        {
            list( $CPaN, $CPa2 ) = $result[0];

        // generate actual Category "path"
        if ( $CPaN )
        {
            $CatTree = "$CPaN";
            while ( $CPa2 )
            {
                $result2=pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                                               array( 'sql' => "SELECT Category,CatParent FROM ".pnConfigGetVar('prefix')."_pncommerce_category WHERE CatInvisible='' AND CategoryID='".(int)pnVarPrepForStore($CPa2)."'"));
                if( $result2<>false )
                {
                    list( $CatPa2, $CatPa3 ) = $result2[0];
                    $CatTree = "$CatPa2 > $CatTree";
                    if ($CatPa3)
                    {
                        $CPa2 = $CatPa3;
                    }
                    else
                    {
                        $CPa2 = "";
                    }
                }
                else
                {
                    return false;
                }
            }
        }
        $CatTree =  "<option value='$ParentID' selected>$CatTree</option>\n";
        }
        else
        {
            return false;
        }
    }
    else
    {
        $CatTree = "<option value='' selected >"._PNC_NOPARENTCATEGORY."</option>\n";
    }
    return $CatTree;
}

/*
 * createOrderStatusListForSelect
 * creates a list of <option></option> for selecting the status of an order
 *
 *@param $args['OrderStatus'] for preselection
 */
function pncommerce_adminapi_createOrderStatusListForSelect( $args )
{
    extract( $args );
    $st[$OrderStatus] = "selected";

    $os .= "<option value='0'  $st[0]  >".pnVarPrepForDisplay( _PNC_ORDER_NEW )."</option>\n";
    $os .= "<option value='10' $st[10] >".pnVarPrepForDisplay( _PNC_ORDER_PAID )."</option>\n";
    $os .= "<option value='90' $st[90] >".pnVarPrepForDisplay( _PNC_ORDER_DONE )."</option>\n";
    $os .= "<option value='99' $st[99] >".pnVarPrepForDisplay( _PNC_ORDER_DELETED )."</option>\n";
    return $os;
}

/*
 * rebuildOrderedQuantity
 * This function rebuilds the field OrderedQuantity in the items table by looking up all
 * open orders and counting the ordered items there
 */

function pncommerce_adminapi_rebuildOrderedQuantity()
{
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::', "::", ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    // Array to store itemIDs and their ordered quantities
    $orderedItems = array();

    // get the number of orders in the db
    $ordercount = pnModAPIFunc('pncommerce', 'user', 'gethighidfromDB',
                               array('table' => 'orders',
                                     'indexfield' => 'OrderNumber'));
    if ($ordercount > 0)
    {
        for ($i = 1; $i <= $ordercount; $i++)
        {
            // read the userid for order $i
            list($UserID) = pnModAPIFunc('pncommerce', 'user', 'readfromDB',
                                            array('table' => 'orders',
                                                  'fields' => array('UserID'),
                                                  'required' => array('OrderNumber', $i)));
            $order = pnModAPIFunc('pncommerce', 'user', 'getOrder',
                                  array('ON' => $i,
                                        'KID' => $UserID));
            // only count items of orders which haven't been deleted
            if (($order <> false) && ($order['OrderStatus'] <> 99))
            {
                // cycle through the order items
                foreach( $order['CartData']['Items'] as $cartItem )
                {
                    $itemID = $cartItem['ItemID'];
                    $quantity = $cartItem['ItemQuantity'];
                    if (isset($orderedItems[$itemID]))
                    {
                        $orderedItems[$itemID] += $quantity;
                    }
                    else
                    {
                        $orderedItems[$itemID] = $quantity;
                    }
                }
            }
        }

        // update the QuantityOrdered in the items table
        foreach($orderedItems as $itemId => $quantity)
        {
            $sql = 'UPDATE ' . pnConfigGetVar('prefix') . '_pncommerce_items SET QuantityOrdered = ' . $quantity . ' WHERE ItemID = ' . $itemId;
            pncommerce_userapi_executesqlDB(array('sql' => $sql));
        }
        return true;
    }
    return false;
}

/**
 * getGroupList
 * read allavailabl groups
 *
 *@param none
 *@return array or false on error
 *@returns['id'] groupid
 *@returns['name'] groupname
 *@returns['user'] array of uid's
 */
function pncommerce_adminapi_getGroupList()
{
    // prepare some variables for db access - we cannot use our own functions here !
    list($dbconn) = pnDBGetConn();
    $pntable = pnDBGetTables();
    $grouptable = $pntable['groups'];
    $groupcolumn = &$pntable['groups_column'];
    $groupmembershiptable = $pntable['group_membership'];
    $groupmembershipcolumn = &$pntable['group_membership_column'];
    $usertable = $pntable['users'];
    $usercolumn = &$pntable['users_column'];

    pncloadapi('user', __FILE__, __LINE__);

    // read the groups
    $query0 = "SELECT $groupcolumn[gid],
              $groupcolumn[name]
              FROM $grouptable";
    $result0 = $dbconn->Execute($query0);
    if (!$result0->EOF)
    {
        $group = array();
        $grouparray = array();
        for(;list($gid, $gname) = $result0->fields;$result0->MoveNext() )
        {
            $group['id'] = $gid;
            $group['name'] = $gname;

            // get users in this group
            $query1 = "SELECT $groupmembershipcolumn[uid]
                      FROM $groupmembershiptable
                      WHERE $groupmembershipcolumn[gid]='".(int)pnVarPrepForStore($gid)."'";
            $result1 = $dbconn->Execute($query1);
            $users = array();
            if( !$result1->EOF )
            {
                for(;list($uid) = $result1->fields;$result1->MoveNext() )
                {
                    $users[] = $uid;
                }
            }
            $result1->Close();
            $group['users'] = $users;
            $grouparray[] = $group;
        }
        $result0->Close();
        return $grouparray;
    }
    return false;
}

/**
 * getGroupsByUser
 * reads all groups a user is member of
 *
 *@param $args['user'] the name of the user, if not set we use the user logged in atm
 *@return array or false on error
 *@returns['id'] groupid
 *@returns['name'] group name
 */
function pncommerce_adminapi_getGroupsByUser( $args )
{
    extract( $args );

    // prepare some variables for db access - we cannot use our own functions here !
    list($dbconn) = pnDBGetConn();
    $pntable = pnDBGetTables();
    $grouptable = $pntable['groups'];
    $groupcolumn = &$pntable['groups_column'];
    $groupmembershiptable = $pntable['group_membership'];
    $groupmembershipcolumn = &$pntable['group_membership_column'];
    $usertable = $pntable['users'];
    $usercolumn = &$pntable['users_column'];

    if( !$user )
    {
        if( pnUserLoggedIn() )
        {
            $uid = pnSessionGetVar( 'uid' );
        }
        else
        {
            // user is not logged in - we have no groups
            return false;
        }
    }
    else
    {
        // get the uid for the user
        $query0 = "SELECT $usercolumn[uid]
                  FROM $usertable
                  WHERE $usercolumn[name] = '".pnVarPrepForStore($user)."'";
        $result0 = $dbconn->Execute($query0);
        if( !$result0->EOF )
        {
            list( $uid ) = $result0->fields;
        }
        $result0->Close();

    }
    pncloadapi('user', __FILE__, __LINE__);

    // read the group membership for $uid
    $query = "SELECT $groupmembershipcolumn[gid]
              FROM $groupmembershiptable
              WHERE $groupmembershipcolumn[uid]='".(int)pnVarPrepForStore($uid)."'";
    $result = $dbconn->Execute($query);
    if (!$result->EOF)
    {
        $group = array();
        $grouparray = array();
        for(;list($gid) = $result->fields;$result->MoveNext() )
        {
            $group['id'] = $gid;
            // Get details on current group
            $query2 = "SELECT $groupcolumn[name]
                      FROM $grouptable
                      WHERE $groupcolumn[gid]='".(int)pnVarPrepForStore($gid)."'";
            $result2 = $dbconn->Execute($query2);
            list($group['name']) = $result2->fields;
            $result2->Close();
            $grouparray[] = $group;
        }
        $result->Close();
        return $grouparray;
    }
    return false;
}

/**
 * addtoModifierSequence
 * add a modifier at the end of the modifier sequence array
 *@param $args['Modifier'] string name of the modifier
 *@param $args['type'] string 'item' or 'order'
 *@return none
 */
function pncommerce_adminapi_addtoModifierSequence( $args )
{
    if (!pnSecAuthAction(0, 'pncommerce::', "::", ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
    extract( $args );
    $modtypearray= array( 'item' => 'ItemModifierSequence',
                          'order' => 'OrderModifierSequence',
                          'preorder' => 'PreOrderModifierSequence',
                          'postorder' => 'PostOrderModifierSequence' );
    if( !isset( $modtypearray[$type] ) )
    {
        return false;
    }

    $modsequence = pnModGetVar( 'pncommerce', $modtypearray[$type] );

    if( isset($modsequence) )
    {
        $modsequence = unserialize( $modsequence );
    }
    else
    {
        $modsequence = array();
    }
    array_push( $modsequence, $Modifier );
    pnModSetVar( "pncommerce", $modtypearray[$type], serialize( $modsequence ) );
    unset( $modsequence );
    return;
}

/**
 * removefromModifierSequence
 * removes a modifier from the modifier sequence array
 *@param $args['Modifier'] string name of the modifier
 *@param $args['type'] string 'item' or 'order'
 *@return none
 */
function pncommerce_adminapi_removefromModifierSequence( $args )
{
    if (!pnSecAuthAction(0, 'pncommerce::', "::", ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
    extract( $args );
    $modtypearray= array( 'item' => 'ItemModifierSequence',
                          'order' => 'OrderModifierSequence',
                          'preorder' => 'PreOrderModifierSequence',
                          'postorder' => 'PostOrderModifierSequence' );
    if( !isset( $modtypearray[$type] ) )
    {
        return false;
    }

    $modsequence = unserialize( pnModGetVar( 'pncommerce', $modtypearray[$type] ) );
    $fliparray = array_flip( $modsequence );
    array_splice( $modsequence, $fliparray[$Modifier], 1 );
    pnModSetVar( 'pncommerce', $modtypearray[$type], serialize( $modsequence ) );
    unset( $modsequence );
    return;
}

/**
 * executeReceiptSearchQuery
 * executes a premade sql query and returns an result array
 *
 *@param $args['sql'] sting query command
 *@returns array of array with the following information (or false on error) :
 *@return['UName']
 *@return['ON']
 *@return['OStatus']
 *@return['Date']
 *@return['DateString']
 *@return['loc']
 *@return['CartData']
 */
function pncommerce_adminapi_executeReceiptSearchQuery( $args )
{
    extract( $args );
    pncloadapi('user', __FILE__, __LINE__);

     if (!pnSecAuthAction(0, 'pncommerce::', "::", ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }

    // execute sql and return the result if any
    $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                            array( 'sql' => $sql ) );
    if ( $result != false )
    {
        $resultarray=array();
        foreach( $result as $resultline )
        {
            // If we change the $select above, we have to adjust the next line also
            list( $UName, $ON, $OStatus, $Date, $CartData ) = $resultline;
            $CartData = unserialize( stripslashes( $CartData ) );
            $DateString =  date( pnModGetVar( 'pncommerce', 'DateFormat' ), $Date )." - ";
            $DateString .= date( pnModGetVar( 'pncommerce', 'TimeFormat' ), $Date );
            $loc = pncAdminModURL( 'pncommerce', 'user', 'receipt',
                                   array('ON' => $ON,
                                         'KID' => $UName,
                                         'User' => $UName,
                                         'Admin'=>true));
            $resultarray[]=array('UName'=>$UName,
                                 'ON'=>$ON,
                                 'OStatus'=>$OStatus,
                                 'Date'=>$Date,
                                 'DateString'=>$DateString,
                                 'loc'=>$loc,
                                 'CartData'=>$CartData);
        }
        return $resultarray;
    }
    return false;
}

/**
 * readactiveModifierInfo
 *
 *@params $args['type'] string (item, order, preorder or postorder)
 *returns array of 2 arrays
 *1st array with modifier names as keys
 *2nd array with array with
 *['name'] name of the modifier, e.g. fmtax
 *['info'] as returned from the info function of the modifier
 *['type'] as returned from the type function of the modifier, normally same as type above
 *['mode'] on, off or empty
 *['state'] _PNC_ACTIVE or PNC_INACTIVE, depending on mode
 *or false on error
 */
function pncommerce_adminapi_readactiveModifierInfo( $args )
{
     if (!pnSecAuthAction(0, 'pncommerce::', "::", ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }
    extract( $args );
    $activefms = array();   // for the data
    $fmnames = array();     // for the names
    switch ($type)
    {
        case 'item':
                $sequencename = 'ItemModifierSequence';
                break;
        case 'order':
                $sequencename = 'OrderModifierSequence';
                break;
        case 'preorder':
                $sequencename = 'PreOrderModifierSequence';
                break;
        case 'postorder':
                $sequencename = 'PostOrderModifierSequence';
                break;
        default:
                return false;
    }
    $modsequence = pnModGetVar( 'pncommerce', $sequencename );
    if( isset( $modsequence ) )
    {
        $modsequence = unserialize( $modsequence );
        foreach( $modsequence as $modseq )
        {
            pncloadapi($modseq, __FILE__, __LINE__);
            $newfm = array();
            $newfm['name'] = $modseq;
            $newfm['info'] = pnModAPIFunc( 'pncommerce', $modseq, 'info' );
            $newfm['type'] = pnModAPIFunc ('pncommerce', $modseq, 'type' );
            $newfm['mode'] = pnModGetVar ('pncommerce', $modseq);
            if ( $newfm['mode'] == 'on' )
            {
                $newfm['state']=""._PNC_ACTIVE;
            }
            else if ( $newfm['mode'] == 'off' )
            {
                $newfm['state']=""._PNC_INACTIVE;
            }
            array_push( $activefms, $newfm );
            array_push( $fmnames, $modseq );
        }
    }
    return array( array_flip( $fmnames ), $activefms );  // might be empty here
}

/**
 * internal function
 *
 * Checks if a given string is a serialized array and return the data found there.
 * Used for the category sorting festure only
 *
 *@param $string categoryname as read from the database
 *@returns array( name, sequence )   ( string, int )
 *
 */
function extractNameAndSequence( $string )
{
    if( @unserialize( $string ) == "" )
    {
        // not seriaized - string contains plain categoryname, no sequence, so we
        // default to 9999
        return array( $string, 9999 );
    }
    // serialized array - unserialize and return what we have found
    $c_hack = unserialize( $string );
    return array( $c_hack['name'], $c_hack['sequence'] );
}

/**
 * schemeGet
 *
 *@params $args['scheme_id'] int optional the id of the scheme to load, -1=new scheme, unset = load all schemes
 *@returns array with scheme data
 */
function pncommerce_adminapi_schemeGet($args)
{
    extract($args);
    unset($args);

    list($dbconn, $pntable) = pncOpenDB();
    $schemestable = $pntable['pncommerce_schemes'];
    $schemescolumn = $pntable['pncommerce_schemes_column'];

    $where = (isset($scheme_id) && ($scheme_id>=0)) ? "WHERE $schemescolumn[scheme_id]='" . (int)pnVarPrepForStore($scheme_id) . "'" : '';

    if($scheme_id==-1) {
        return (array('scheme_id' => -1,
                      'template_id' => 0,
                      'timestamp' => '',
                      'name' => pnVarPrepForDisplay(_PNC_NEWSCHEME),
                      'description' => pnVarPrepForDisplay(_PNC_NEWSCHEMEDESCRIPTION)));
    } else {
        $schemes = array();
        $sql = "SELECT " . $schemescolumn['scheme_id'] . " as scheme_id,
                       " . $schemescolumn['template_id'] . " as template_id,
                       " . $schemescolumn['timestamp'] . " as timestamp,
                       " . $schemescolumn['name'] . " as name,
                       " . $schemescolumn['type'] . " as type,
                       " . $schemescolumn['description'] . " as description
                FROM $schemestable
                $where";
//                WHERE " . $schemescolumn['scheme_id'] . "='" . (int)pnVarPrepForStore($scheme_id) . "'";
        $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
        if($result->EOF) {
            pncCloseDB($result);
            return $schemes;
        }
        while (!$result->EOF) {
            $scheme = $result->GetRowAssoc(false);
            $scheme['properties'] = pncommerce_adminapi_getpropertiesforscheme(array('scheme_id' => $scheme['scheme_id']));
            $schemes[] = $scheme;
            $result->MoveNext();
        }
        pncCloseDB($result);
    }

    if(isset($scheme_id)) {
        // scheme_id is set, only return this entry
        return $schemes[0];
    }
    return $schemes;
}
/**
 * schemeGet
 *
 *@params $args['scheme_id'] int optional the id of the scheme to load, -1=new scheme, unset = load all schemes
 *@returns array with scheme data
 */
function pncommerce_adminapi_supplierGet($args)
{
    extract($args);
    unset($args);

    list($dbconn, $pntable) = pncOpenDB();
    $supplierstable = $pntable['pncommerce_suppliers'];
    $supplierscolumn = $pntable['pncommerce_suppliers_column'];

    $where = (isset($supplier_id) && ($supplier_id>=0)) ? "WHERE $supplierscolumn[supplier_id]='" . (int)pnVarPrepForStore($supplier_id) . "'" : '';

    if($supplier_id==-1) {
        return (array('supplier_id' => -1,
                      'name' => pnVarPrepForDisplay(_PNC_NEWSUPPLIER),
                      'url' => pnVarPrepForDisplay(_PNC_NEWSUPPLIERURL)));
    } else {
        $suppliers = array();
        $sql = "SELECT " . $supplierscolumn['supplier_id'] . " as supplier_id,
                       " . $supplierscolumn['supplier_name'] . " as name,
                       " . $supplierscolumn['supplier_url'] . " as url
                FROM $supplierstable
                $where";
        $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
        if($result->EOF) {
            pncCloseDB($result);
            return $suppliers;
        }
        while (!$result->EOF) {
            $supplier = $result->GetRowAssoc(false);
            $suppliers[] = $supplier;
            $result->MoveNext();
        }
        pncCloseDB($result);
    }

    if(isset($supplier_id)) {
        // scheme_id is set, only return this entry
        return $suppliers[0];
    }
    return $suppliers;
}

/**
 * schemeSet
 *
 *@params $args['scheme'] array with scheme data
 *@returns boolean true or false
 */
function pncommerce_adminapi_schemeSet($args)
{
    extract($args);
    unset($args);

    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    list($dbconn, $pntables) = pncOpenDB();
    $schemestable = $pntables['pncommerce_schemes'];
    $schemescolumn = $pntables['pncommerce_schemes_column'];

    if($scheme['scheme_id']==-1) {
        $sql = "INSERT INTO $schemestable
                    (".$schemescolumn['name'].",
                     ".$schemescolumn['type'].",
                     ".$schemescolumn['description'].",
                     ".$schemescolumn['template_id'].")
                VALUES ('" . pnVarPrepForStore($scheme['name']) . "',
                        '" . (int)pnVarPrepForStore($scheme['type']) . "',
                        '" . pnVarPrepForStore($scheme['description']) . "',
                        '" . (int)pnVarPrepForStore($scheme['template_id']) . "')";
        $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
        pncCloseDB($result);
        $scheme_id = $dbconn->PO_Insert_ID($pntable['pncommerce_schemes'], 'scheme_id');
        return $scheme_id;
    } else {
        $sql = "UPDATE $schemestable
                SET ".$schemescolumn['name']."='" . pnVarPrepForStore($scheme['name']) . "',
                    ".$schemescolumn['type']."='" . (int)pnVarPrepForStore($scheme['type']) . "',
                    ".$schemescolumn['description']."='" . pnVarPrepForStore($scheme['description']) . "',
                    ".$schemescolumn['template_id']."='" . pnVarPrepForStore($scheme['template_id']) . "'
                WHERE ".$schemescolumn['scheme_id']."='" . (int)pnVarPrepForStore($scheme['scheme_id']) . "'";
        $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
        pncCloseDB($result);
        return $scheme['scheme_id'];
    }
    return -1;
}

/**
 * schemeDelete
 *
 *@params $args['scheme_id'] int scheme id to delete
 */
function pncommerce_adminapi_schemeDelete($args)
{
    extract($args);
    unset($args);

    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    if(!isset($scheme_id) || !is_numeric($scheme_id)) {
        return showerrorpage(_MODARGSERROR, __FILE__, __LINE__);
    }

    $scheme = pnModAPIFunc('pncommerce', 'admin', 'schemeGet',
                           array('scheme_id' => $scheme_id));
    foreach($scheme['properties'] as $property) {
        pnModAPIFunc('pncommerce', 'admin', 'propertyDelete',
                     array('property_id' => $property['property_id']));
    }
    list($dbconn, $pntables) = pncOpenDB();
    $schemestable = $pntables['pncommerce_schemes'];
    $schemescolumn = $pntables['pncommerce_schemes_column'];

    $sql = "DELETE FROM $schemestable
            WHERE " . $schemecolumn['scheme_id'] . "='" . (int)pnVarPrepForStore($scheme['template_id']) . "')";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__, true);
    pncCloseDB($result);


}

/**
 * getpropertiesforscheme
 *
 *@params $args['scheme_id'] int the id of the scheme to read the props for
 *@returns array with properties information for the given scheme or flse on error
 */
function pncommerce_adminapi_getpropertiesforscheme($args)
{
    extract($args);
    unset($args);

    if(!isset($scheme_id) || !is_numeric($scheme_id) || $scheme_id<0) {
        return showerrorpage(_MODARGSERROR, __FILE__, __LINE__);
    }

    list($dbconn, $pntable) = pncOpenDB();
    $propertiestable = $pntable['pncommerce_properties'];
    $propertiescolumn = $pntable['pncommerce_properties_column'];

    $properties = array();
    $sql = "SELECT " . $propertiescolumn['property_id'] . " as property_id,
                   " . $propertiescolumn['scheme_id'] . " as scheme_id,
                   " . $propertiescolumn['timestamp'] . " as timestamp,
                   " . $propertiescolumn['name'] . " as name,
                   " . $propertiescolumn['type'] . " as type,
                   " . $propertiescolumn['config'] . " as config,
                   " . $propertiescolumn['hidden'] . " as hidden,
                   " . $propertiescolumn['sortorder'] . " as sortorder
            FROM $propertiestable
            WHERE " . $propertiescolumn['scheme_id'] . "='" . (int)pnVarPrepForStore($scheme_id) . "'
            ORDER BY " . $propertiescolumn['sortorder'] . " ";
    $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
    while (!$result->EOF) {
        $property = $result->GetRowAssoc(false);
        //unserialize if necessary
        $unserialized=unserialize($property['config']);
        if(is_array($unserialized))$property['config']=$unserialized;

        pncloadapi($property['type'], __FILE__, __LINE__);
        $property['info'] = pnModAPIFunc('pncommerce', $property['type'], 'info');

        array_push($properties, $property);
        $result->MoveNext();
    }
    pncCloseDB($result);
    return $properties;
}


/**
 * created the entries in the propertydata table for this scheme for the given object
 * @param $args['scheme_id'] int
 * @param $args['object_id'] int
 * @return boolean true on success
 */
function pncommerce_adminapi_refreshProperties($args)
{
    if (!pnSecAuthAction(0,
                       'pncommerce::item',
                       '::', ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);

    }

    $properties = pncommerce_adminapi_getpropertiesforscheme(array('scheme_id' => $args['scheme_id']));
    foreach($properties as $property)
    {
        pncloadapi($property['type'], __FILE__, __LINE__);
        $property['object_id']=$args['object_id'];
        $property=pnModAPIFunc('pncommerce', $property['type'], 'newdata', array('property' => $property));
        pncommerce_adminapi_propertydataAdd($property);

    }
    return true;
}




/**
 * sorting categories by cat_order
 *
 */
function cmp_schemesortorder ($a, $b)
{
   return $a['sortorder'] > $b['sortorder'];
}

/**
 * storepropertiessortorder
 *
 *@params $args['properties'] array with scheme information
 */
function pncommerce_adminapi_storepropertiessortorder($args)
{
    extract($args);
    unset($args);

    // sort the properties array
    usort($properties, 'cmp_schemesortorder');
//pncdebug('nach schemesortorder', $properties);

    list($dbconn, $pntables) = pncOpenDB();
    $propertiesstable = $pntables['pncommerce_properties'];
    $propertiesscolumn = $pntables['pncommerce_properties_column'];

    // recalculate the sortorders
    for($i=0; $i<count($properties); $i++) {
        $properties[$i]['sortorder'] = ($i+1) * 2;
    // store the new properties

        $sql = "UPDATE $propertiesstable
                SET ".$propertiesscolumn['sortorder']."='" . (int)pnVarPrepForStore($properties[$i]['sortorder']) . "'
                WHERE ".$propertiesscolumn['property_id']."='" . (int)pnVarPrepForStore($properties[$i]['property_id']) . "'";
        $result = pncExecuteSQL($dbconn, $sql, __FILE__, __LINE__);
        pncCloseDB($result);
    }
//pncdebug('final version', $properties, true);
    return true;

}

/**
 * recalculatepropertiessortorder
 *
 *@params $args['scheme_id'] int the scheme id
 *
 */
function pncommerce_adminapi_recalculatepropertiessortorder($args)
{
    extract($args);
    unset($args);

    if(!isset($scheme_id) || !is_numeric($scheme_id)) {
        return showerrorpage(_MODARGSERROR, __FILE__, __LINE__);
    }

    $properties = pnModAPIFunc('pncommerce', 'admin', 'getpropertiesforscheme',
                               array('scheme_id' => $scheme_id));
    pnModAPIFunc('pncommerce', 'admin', 'storepropertiessortorder',
                 array('properties' => $properties));

}


?>
